﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using CMISLibrary.Libraries;
using BaocaoNPC.Usercontrols.reports;
using BaocaoNPC.common;
using CMISLibrary;
using BCNPCEntities;
using System.Threading;
using bus_TienichNPC;
using Microsoft.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for CHAMNO_KHANG_TAIQUAY.xaml
    /// </summary>
    public partial class CHAMNO_KHANG_TAIQUAY : UserControl
    {
        #region Khai báo biến
        public String strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public String strTenDNHap = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "PA";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        public String strMa_TNgan = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap.ToUpper() : "PA";
        DataSet ds_BBTHUNGAN = new DataSet();
        DataSet ds_HDONCHAMNO = new BCNPCEntities.EXCEL.DS_CHAMNO();
        DataSet ds_CAPNHAT = new BCNPCEntities.EXCEL.ds_CAPNHAT();
        DataSet dsResult = new DataSet();
        int dkien;
        int timkiem = 0;
        int thang = 0, nam = 0;
        bool forcus = false;
        bool group = false;
        bool nhomthanhtoan = false;
        bool khongnhom = false;
        bool _fSetText = true, _fSetTextG = true;
        bool chamno = false;
        string forcus_ = "", messger = "";
        //cls_ImportExcel_bus cls = new cls_ImportExcel_bus();
        string maloi = "";
        Decimal text;
        #endregion

        public CHAMNO_KHANG_TAIQUAY()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //dgrHDON_CNO.Columns[2].Header = "CÔNG NGHỆ \n\r abc";
            cboHoaDon.SelectedIndex = 0;
            dtpNgayNOP.SelectedDate = System.DateTime.Now;
            DataSet ds = new DataSet();
            //ds = cls.select_ThuNganVien(strMa_dviqly);
            ds = GlobalServices.Service_NPCUS.select_ThuNganVien(strMa_dviqly);
            ds.Tables[0].DefaultView.RowFilter = "MA_TNGAN ='" + strTenDNHap.Trim() + "'";
            lblMATNV.Content = strTenDNHap.Trim();
            lblTENTNV.Content = ds.Tables[0].DefaultView[0]["TEN_TNGAN"].ToString();
            //cls.select_THANGNAMCONGNO(strMa_dviqly, ref thang, ref nam);
            GlobalServices.Service_NPCUS.select_THANGNAMCONGNO(strMa_dviqly, ref thang, ref nam);
            lblthangnam.Content = "Tháng năm công nợ: " + thang.ToString() + "/" + nam.ToString();
            Xoa_text();
            if (strMa_dviqly == "PA24HN")
            { chkKhangPthu.Visibility = Visibility.Visible; }
            else
            { chkKhangPthu.Visibility = Visibility.Hidden; }
        }

        private void cboHoaDon_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LOAD_DATA();
        }

        private void LOAD_DATA()
        {
            try
            {
                SetStatus("THUCHIEN", cboHoaDon, "Đang thực hiện lấy số biên bản ...");
                switch (cboHoaDon.SelectedIndex)
                {
                    case 0: //chon hd chua cham
                        dkien = 0;
                        ds_BBTHUNGAN = new DataSet();
                        //ds_BBTHUNGAN = cls.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 0, ref maloi);
                        ds_BBTHUNGAN = GlobalServices.Service_NPCUS.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 0, ref maloi);
                        if (ds_BBTHUNGAN.Tables[0].Rows.Count == 0) return;
                        fill_dulieu(ds_BBTHUNGAN);
                        break;

                    case 1: //chon hd da cham
                        dkien = 1;
                        ds_BBTHUNGAN = new DataSet();
                        //ds_BBTHUNGAN = cls.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 1, ref maloi);
                        ds_BBTHUNGAN = GlobalServices.Service_NPCUS.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 1, ref maloi);
                        fill_dulieu(ds_BBTHUNGAN);
                        break;

                    case 2: //chon all hdon  
                        dkien = 2;
                        ds_BBTHUNGAN = new DataSet();
                        //ds_BBTHUNGAN = cls.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 2, ref maloi);
                        ds_BBTHUNGAN = GlobalServices.Service_NPCUS.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 2, ref maloi);
                        fill_dulieu(ds_BBTHUNGAN);
                        break;
                    case 3: //chon all hdon  
                        dkien = 3;
                        ds_BBTHUNGAN = new DataSet();
                        //ds_BBTHUNGAN = cls.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 2, ref maloi);
                        ds_BBTHUNGAN = GlobalServices.Service_NPCUS.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 3, ref maloi);
                        fill_dulieu(ds_BBTHUNGAN);
                        break;
                }
                ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Clear();
                dgrHDON_CNO.ItemsSource = null;
                Xoa_text();
                //lblTONGSOHDON_DACHAM.Content = "0";
                //lblTONGSOTIEN_DACHAM.Content = "0";
                //lblTONGSOHDON.Content = "0";
                Update_autotext();
                txtGiaTri.FocusAutoText();
                SetStatus("COMPLATE", cboHoaDon , "");
            }
            catch
            { SetStatus("ERROR", cboHoaDon, maloi); }
        }

        private void Xoa_text()
        {
            txtMA_KHANG.Text = "";
            txtTEN_KHANG.Text = "";
            txtDCHI_KHANG.Text = "";
            txtSO_SERY.Text = "";
            txtMA_SOGCS.Text = "";
            txtSTT.Text = "";
            txtMA_TRAM.Text = "";
            txtSO_COT.Text = "";
            txtSO_HOM.Text = "";
            txtTONGTIENGIAO.Text = "";
            txtTONGTIENNOP.Text = "";
            txtTONGTIENNO.Text = "";
            txtTIENHOADON.Text = "";
            txtTIENNOP.Text = "";
            txtTIENTRALAI.Text = "";
            txtTimKiemTenPTu.Text = "";
            lblTongso.Content = "Tổng số 0/0";
        }
        private void fill_dulieu(DataSet ds)// hàm này đưa dữ liệu từ đầu vào dataset();
        {
            try
            {
                if (ds.Tables.Count == 0) return;
                TreeViewItem superNode = new TreeViewItem();
                TreeViewItem _node = new TreeViewItem();
                TreeViewItem _childnode = new TreeViewItem();
                CheckBox chkNode = new CheckBox();
                CheckBox chkChildNode = new CheckBox();
                CheckBox chkSuperNode = new CheckBox();
                // filter_treeDataSet();
                this.trvBBAN.Items.Clear(); // xoa tree trước khi đỗ dữ liệu mới
                DataView dv = new DataView(ds.Tables[0]);
                dv.Sort = "SO_BBGIAO";
                if (dv.Count == 0) // không có dữ liệu không đưa ra tree
                {

                    superNode.Header = "Không có dữ liệu biên bản";
                    superNode.Tag = "Không có dữ liệu biên bản@";
                    trvBBAN.Items.Add(superNode);
                    return;
                }
                chkSuperNode = new CheckBox();
                chkSuperNode.Content = "Tất cả biên bản";
                chkSuperNode.Tag = "@N@NUTGOC";
                chkSuperNode.ToolTip = "Biên bản";
                chkSuperNode.IsChecked = false;
                chkSuperNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                superNode = new TreeViewItem();
                superNode.Header = chkSuperNode;
                superNode.IsExpanded = true;
                //superNode.IsSelected = true;
                trvBBAN.Items.Add(superNode);
                string strnutcha = "";
                string strnutcon = "";
                string str_bienban = "";
                string str_ma_sogcs = "";
                string str_ma_dviqly = "";
                foreach (DataRowView dr in dv)
                {
                    str_bienban = dr["SO_BBGIAO"].ToString();
                    str_ma_dviqly = dr["MA_DVIQLY"].ToString();
                    str_ma_sogcs = dr["MA_SOGCS"].ToString();
                    //DataRow[] row = dsResultTree.Tables["table1"].Select("MA_DVI_QLYLUOI = '" + str_ma_dviqly_luoi + "'");
                    //str_soluong = dr["TONGSO"].ToString();
                    //str_socto = dr["SO_LUONG"].ToString();
                    #region "parentnode"
                    if (str_bienban != strnutcha)
                    {
                        chkNode = new CheckBox();
                        chkNode.Content = str_bienban + " -" + dr["NGAY_GIAO"].ToString(); ;
                        chkNode.Tag = str_bienban + "@" + chkSuperNode.ToolTip.ToString() + "@NUTCHA";
                        chkNode.ToolTip = str_bienban;
                        chkNode.IsChecked = false;
                        chkNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                        _node = new TreeViewItem();
                        _node.Header = chkNode;
                        _node.IsExpanded = true;
                        superNode.Items.Add(_node);
                        strnutcha = str_bienban;
                    }
                    # endregion
                    #region childNode
                    if (str_ma_sogcs != strnutcon)
                    {
                        //DataRow[] row1 = dsResultTree.Tables["table1"].Select("MA_DVI_QLYLUOI = '" + str_ma_dviqly_luoi + "'");
                        chkChildNode = new CheckBox();
                        chkChildNode.Content = str_ma_sogcs;
                        chkChildNode.Tag = str_ma_sogcs + "@" + chkNode.ToolTip.ToString() + "@NUTCON";
                        chkChildNode.ToolTip = str_ma_sogcs;
                        chkChildNode.IsChecked = false;
                        chkChildNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                        _childnode = new TreeViewItem();
                        _childnode.Header = chkChildNode; //+ " (" + str_soluong + " hồ sơ)";
                        _childnode.IsExpanded = true;
                        _node.Items.Add(_childnode); //them nut con
                        strnutcon = str_ma_sogcs;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
        public void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                chk.Cursor = Cursors.Wait;
                lblstatus.Content = "Đang lấy dữ liệu hóa đơn...";
                TreeViewItem itemselect = trvBBAN.SelectedItem as TreeViewItem;
                string soBBanPbo = "", ngayPbo = "";
                //get_chkItem(chk, ref soBBanPbo, ref ngayPbo);
                //dt = new DataTable();
                //dt = this.dsResult.Tables["CTO"].Clone();
                // cắt mảng tag
                string[] m = chk.Tag.ToString().Split('@');
                if (chk.IsChecked == true)
                {
                    //kiem tra xem root or leaf duoc check
                    //#region Check All ChildNode
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        checkList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    dsResult = new DataSet();
                    // update tongso
                    DataSet dstong = GlobalServices.Service_NPCUS.TONGTIENCHAM(strMa_dviqly, strMa_TNgan,thang,nam,ref maloi);
                    //DataSet dstong = cls.TONGTIENCHAM(strMa_dviqly, strMa_TNgan, thang, nam, ref maloi);
                    if (dstong != null)
                    {
                        if (dstong.Tables[0].Rows.Count > 0)
                        {
                            txtTONGTIENGIAO.Text = Convert.ToDecimal(dstong.Tables[0].Rows[0]["TONGTIENGIAO"]).ToString("# ### ### ###");
                            txtTONGTIENNOP.Text = Convert.ToDecimal(dstong.Tables[0].Rows[0]["TONGTIENNOP"]).ToString("# ### ### ###");
                            txtTONGTIENNO.Text = Convert.ToDecimal(dstong.Tables[0].Rows[0]["TONGTIENCONLAI"]).ToString("# ### ### ###");
                        }
                    }
                    // nếu click nút tổng
                    if (chk.Tag.ToString() == "@N@NUTGOC")
                    {
                        //dsResult = cls.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan,0,"","ALL", dkien,ref maloi);
                        dsResult = GlobalServices.Service_NPCUS.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, 0, "", "ALL", dkien, ref maloi);
                        //ds_HDONCHAMNO = new DataSet();
                        //ds_HDONCHAMNO = dsResult.Copy();
                        ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Clear();
                        copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                        ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                        if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                        {
                            dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                            //TootsNPC.NPCDatagrid.GetBackgroundCell(dgrHDON_CNO, 1, 1,Brushes.Chocolate);
                            //TootsNPC.NPCDatagrid.GetBackgroundcolumn(dgrHDON_CNO, 2, Brushes.Chocolate);
                            //TootsNPC.NPCDatagrid.GetBackgroundRow(dgrHDON_CNO, 0);
                        }
                        else
                        { dgrHDON_CNO.ItemsSource = null; }
                        //dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                    }

                    // nếu clich nút cha
                    if (m[2].ToString() == "NUTCHA")
                    {
                        // lấy dữ liệu của nút cha
                        //dsResult = cls.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, Convert.ToInt32(m[0].ToString()), "", "BIENBAN", dkien, ref maloi);
                        dsResult = GlobalServices.Service_NPCUS.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, Convert.ToInt32(m[0].ToString()), "", "BIENBAN", dkien, ref maloi);
                        //
                        if (ds_HDONCHAMNO.Tables.Count == 0)
                        {
                            if (dsResult != null)
                            {
                                copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                                ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                                if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                                {
                                    dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                                }
                                else
                                { dgrHDON_CNO.ItemsSource = null; }
                            }
                            else
                            { dgrHDON_CNO.ItemsSource = null; }
                        }
                        else if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count == 0)// chưa có hóa đơn nào
                        {
                            if (dsResult != null)
                            {
                                copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                                ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                                if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                                {
                                    dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                                }
                                else
                                { dgrHDON_CNO.ItemsSource = null; }
                            }
                            else
                            { dgrHDON_CNO.ItemsSource = null; }
                        }
                        else
                        {
                            for (int i = ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count - 1; i >= 0; i--)
                            {
                                if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i]["SO_BBGIAO"].ToString() == m[0].ToString())
                                {
                                    ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i].Delete();
                                }
                            } //end of for loop     
                            ds_HDONCHAMNO.AcceptChanges();
                            copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                            ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                            if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                            {
                                dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                            }
                            else
                            { dgrHDON_CNO.ItemsSource = null; }
                        }
                    }
                    // nếu clich nút con
                    if (m[2].ToString() == "NUTCON")
                    {
                        // lấy dữ liệu của nút cha
                        //string a = itemselect.Parent.ToString();
                        //dsResult = cls.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, Convert.ToInt32(m[1].ToString()), m[0].ToString().Trim(), "SOGCS", dkien, ref maloi);
                        dsResult = GlobalServices.Service_NPCUS.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, Convert.ToInt32(m[1].ToString()), m[0].ToString().Trim(), "SOGCS", dkien, ref maloi);
                        //
                        if (ds_HDONCHAMNO.Tables.Count == 0)
                        {
                            if (dsResult != null)
                            {
                                copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                                ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                                if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                                {
                                    dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                                }
                                else
                                { dgrHDON_CNO.ItemsSource = null; }
                            }
                            else
                            { dgrHDON_CNO.ItemsSource = null; }
                        }
                        else if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count == 0)// chưa có hóa đơn nào
                        {
                            //ds_HDONCHAMNO = new DataSet();
                            if (dsResult != null)
                            {
                                copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                                ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                                if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                                {
                                    dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                                }
                                else
                                { dgrHDON_CNO.ItemsSource = null; }
                            }
                            else
                            { dgrHDON_CNO.ItemsSource = null; }
                        }
                        else
                        {
                            copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                            ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                            if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                            {
                                dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                            }
                            else
                            { dgrHDON_CNO.ItemsSource = null; }
                        }
                    }
                }
                else
                {
                    //DataRow dr =null;
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        UncheckList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (chk.Tag.ToString() == "@N@NUTGOC")
                    {
                        ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Clear();
                        dgrHDON_CNO.ItemsSource = null;
                    }

                    // nếu clich nút cha
                    if (m[2].ToString() == "NUTCHA")
                    {
                        for (int i = ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i]["SO_BBGIAO"].ToString().Trim() == m[0].ToString().Trim())
                            {
                                ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_HDONCHAMNO.AcceptChanges();
                        ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                        if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                        {
                            dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                        }
                    }
                    // nếu clich nút con
                    if (m[2].ToString() == "NUTCON")
                    {
                        for (int i = ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i]["SO_BBGIAO"].ToString().Trim() == m[1].ToString().Trim() && ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i]["MA_SOGCS"].ToString().Trim() == m[0].ToString().Trim())
                            {
                                ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_HDONCHAMNO.AcceptChanges();
                        ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                        if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                        {
                            dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                            
                        }
                        else
                        { dgrHDON_CNO.ItemsSource = null; }
                    }
                }
                // tính tổng hóa đơn nộp
                if (ds_HDONCHAMNO.Tables.Count == 0)
                {
                    //lblTONGSOHDON_DACHAM.Content = "0";
                    //lblTONGSOTIEN_DACHAM.Content = "0";
                    //lblTONGSOHDON.Content = "0";
                    //chkDaoChon.IsChecked = false;
                    //chkChonAll.IsChecked = false;
                    Xoa_text();
                }
                else
                {
                    if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count == 0)
                    {
                        //txtTONGTIENGIAO.Text = "";
                        //txtTONGTIENNOP.Text = "";
                        //chkDaoChon.IsChecked = false;
                        //chkChonAll.IsChecked = false;
                        Xoa_text();
                    }
                    else
                    {
                        txtTimKiemTenPTu.Text = "";
                        txtTimKiemTenPTu.Focus();
                        bodem(ds_HDONCHAMNO);
                    }
                }
                chk.Cursor = null;
                //
            }
            catch
            {
                this.Cursor = Cursors.Arrow;
                lblstatus.Content = "";
                return;

            }
            this.Cursor = Cursors.Arrow;
            lblstatus.Content = "";
        }
        private void copy_dataset(DataSet dsnguon,DataTable dt)
        {
            try
            {
                DataRow[] rgINS = dsnguon.Tables[0].Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["CHON"] = rgINS[i]["CHON"].ToString();
                    dr["STT"] = rgINS[i]["STT"].ToString();
                    dr["KYTHANGNAM"] = rgINS[i]["KYTHANGNAM"].ToString();
                    dr["MA_DVIQLY"] = rgINS[i]["MA_DVIQLY"].ToString();
                    dr["MA_KHANG"] = rgINS[i]["MA_KHANG"].ToString();
                    dr["TEN_KHANG"] = rgINS[i]["TEN_KHANG"].ToString();
                    dr["DCHI_KHANG"] = rgINS[i]["DCHI_KHANG"].ToString();
                    dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"].ToString();
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"].ToString();
                    string a = Convert.ToDecimal(rgINS[i]["TONGTIEN"]).ToString("# ### ### ###");
                    dr["TONGTIEN"] = a;
                    string b = "";
                    if (rgINS[i]["TONGNOP"].ToString() != "") b = Convert.ToDecimal(rgINS[i]["TONGNOP"]).ToString("# ### ### ###");
                    dr["TONGNOP"] = b;
                    dr["TIEN_NO"] = rgINS[i]["TIEN_NO"];
                    dr["THUE_NO"] = rgINS[i]["THUE_NO"];
                    dr["SO_SERY"] = rgINS[i]["SO_SERY"];
                    dr["ID_HDON"] = rgINS[i]["ID_HDON"];
                    dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];
                    dr["NGAY_GIAO"] = rgINS[i]["NGAY_GIAO"];
                    dr["TRANGTHAI"] = rgINS[i]["TRANGTHAI"];
                    dr["MA_TRAM"] = rgINS[i]["MA_TRAM"];
                    dr["SO_COT"] = rgINS[i]["SO_COT"];
                    dr["SO_HOM"] = rgINS[i]["SO_HOM"];
                    dt.Rows.Add(dr);
                    ds_HDONCHAMNO.AcceptChanges();
                }
            }
            catch
            {
                
            }
        }

        private void UncheckList(TreeViewItem nodes, CheckBox chk)
        {
            //dt.Rows.Clear();
            if ((CheckBox)nodes.Header == chk)
            {
                UnCheckAllChildsWhenParentUnCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    UnCheckParent(node);
                    if (node.Items.Count > 0)
                    {
                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = false;
                            if (subNode.Items.Count > 0)
                            {
                                UncheckList(subNode, chk);
                            }
                            //load database of childnode
                            //KiemTra_Insert_tbl_All_TheoDoiNo(chkChildNode);
                        }
                    }
                    else
                    {
                        CheckBox chkNode = (CheckBox)node.Header;
                        chkNode.IsChecked = false;
                    }
                }
                else
                {
                    UncheckList(node, chk);
                }

            }
        }
        private void UnCheckParent(TreeViewItem node)
        {
            TreeViewItem parentNode = node.Parent as TreeViewItem;
            if (parentNode != null)
            {
                CheckBox chkParentNode = (CheckBox)parentNode.Header;
                chkParentNode.IsChecked = false;
                UnCheckParent(parentNode);
            }
        }
        private void RefreshCheckBoxList(TreeViewItem nodes)
        {
            DataRow[] dr = null;
            foreach (TreeViewItem subNode in nodes.Items)
            {
                //check all Node
                CheckBox chkNode = (CheckBox)subNode.Header;
                if (subNode.Items.Count > 0)
                {
                    RefreshCheckBoxList(subNode);
                }
                else
                {
                    if (chkNode.IsChecked == true)
                    {
                        //if (tabTimKiem1.SelectedIndex == 0)
                        //{
                        //    if (cboTTrangCTo.SelectedIndex == 0)
                        //        dr = this.dsResult.Tables["CTO"].Select("SO_BBAN = '" + chkNode.Content.ToString() + "'");
                        //    else
                        //        //dr = this.dsResult.Tables["CTO"].Select("SO_BBAN = '" + chkNode.Content.ToString() + "'");

                        //        dr = this.dsResult.Tables["CTO"].Select("SO_BBAN_KDINH = '" + chkNode.Content.ToString() + "'");
                        //}
                        //else
                        //{
                        //    dr = this.dsResult.Tables["CTO"].Select("ID_BBAN_PBO = " + chkNode.Content.ToString() + "");
                        //    // lay thong tin ID phan bo
                        //    DataRow drBB = dsSearh.Tables["DD_BBAN_PBO"].NewRow();
                        //    drBB["MA_DVIQLY"] = strMaDViQLy;
                        //    drBB["ID_BBAN_PBO"] = Convert.ToInt64(chkNode.Content.ToString());
                        //    drBB["MA_DVIQLY_NHAN"] = dr[0]["MA_DVIQLY_NHAN"].ToString();
                        //    dsSearh.Tables["DD_BBAN_PBO"].Rows.Add(drBB);
                        //    dsSearh.AcceptChanges();
                        //}
                        //foreach (DataRow dro in dr)
                        //{
                        //    dt.ImportRow(dro);
                        //}
                    }
                    else
                    {
                        //if (tabTimKiem1.SelectedIndex == 1)
                        //{
                        //    //DataRow[] drDelete = null;
                        //    DataRow drDelete = dsSearh.Tables["DD_BBAN_PBO"].Select("ID_BBAN_PBO = " + chkNode.Content.ToString() + "").FirstOrDefault();
                        //    if (drDelete != null)
                        //    {
                        //        drDelete.Delete();
                        //    }
                        //    dsSearh.AcceptChanges();
                        //}
                    }
                }
                //load database of childnode
                //KiemTra_Insert_tbl_All_TheoDoiNo(chkChildNode);
            }
        }
        private void checkList(TreeViewItem nodes, CheckBox chk)
        {
            //dt.Rows.Clear();
            //DataRow[] dr = null;
            if ((CheckBox)nodes.Header == chk)
            {
                CheckAllChildsWhenParentCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    if (node.Items.Count > 0)
                    {

                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = true;
                            if (subNode.Items.Count > 0)
                            {
                                checkList(subNode, chk);
                            }
                        }
                        CheckParentWhenAllChildChecked(nodes);
                    }
                    else
                    {

                        CheckParentWhenAllChildChecked(nodes);
                    }
                }
                else
                {
                    checkList(node, chk);
                }

            }
            //dt.AcceptChanges();
        }
        private void CheckParentWhenAllChildChecked(TreeViewItem nodes)
        {
            int count = 0;
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                if (chkNode.IsChecked == false)
                {
                    count = count + 1;
                    break;
                }
            }
            if (count == 0)
            {
                CheckBox chkNode = (CheckBox)nodes.Header;
                chkNode.IsChecked = true;
                TreeViewItem parentNode = nodes.Parent as TreeViewItem;
                if (parentNode != null)
                {

                    CheckParentWhenAllChildChecked(parentNode);
                }
            }
        }

        private void CheckAllChildsWhenParentCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = true;
                CheckAllChildsWhenParentCheck(node);
            }
        }
        private void UnCheckAllChildsWhenParentUnCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = false;
                UnCheckAllChildsWhenParentUnCheck(node);
            }
        }
        private void Update_autotext()
        {
            try
            {
                if (ds_BBTHUNGAN.Tables.Count == 0)
                {
                    txtGiaTri.ClearItem();
                    return; 
                }
                string ma_so = "";
                DataTable dt = new DataTable();
                //DataTable desiredResult = GroupBy("TeamID", "MemberID", dt);
                DataColumn Col1 = dt.Columns.Add("MA_SOGCS", typeof(String));
                dt.Columns.Add("TEN_SOGCS", typeof(String));
                //DataRow[] rgINS = ds_autotext.Tables[0].Select("group by MA_SOGCS AND avg(MA_SOGCS)");
                var result = (from row in ds_BBTHUNGAN.Tables[0].AsEnumerable()
                              group row by row["MA_SOGCS"] into temp
                              select new
                              {
                                  MA_SOGCS = temp.Key.ToString(),
                                  TEN_SOGCS = "",
                              }).ToList();

                //DataRow[] results = ds.Tables[0].Select("group by columnName AND avg(columnName)");
                for (int i = 0; i < result.Count; i++)
                {
                    //dt.Rows.Clear();
                    DataRow dr = dt.NewRow();
                    dr["MA_SOGCS"] = result[i].MA_SOGCS;
                    dr["TEN_SOGCS"] = result[i].TEN_SOGCS;
                    dt.Rows.Add(dr);
                    dt.AcceptChanges();
                }
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                ds.AcceptChanges();
                ProcessData(ds);
                txtGiaTri.ClearItem();
                if (ds != null) txtGiaTri.AddItem(new CMIS2_TextBox.AutoCompleteEntry(ds.Tables[0], "DataTable"));
            }
            catch
            { }
        }
        private void ProcessData(DataSet ds)
        {
            try
            {
                foreach (DataTable dt in ds.Tables)
                {
                    if (dt.Columns.Count > 0)
                    {
                        dt.Columns.AddRange(new DataColumn[] { new DataColumn("SEARCH", typeof(string)), new DataColumn("MA_SEARCH", typeof(string)), new DataColumn("TEN_SEARCHED", typeof(string)) });
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["SEARCH"] = dr["MA_SOGCS"].ToString() + dr["TEN_SOGCS"].ToString();
                            dr["MA_SEARCH"] = dr["SEARCH"];
                            dr["TEN_SEARCHED"] = dr["TEN_SOGCS"];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        protected void SetStatus(string Begin, System.Windows.Controls.Control ControlA, string strNote)
        {
            switch (Begin)
            {
                case "ERROR":
                    this.Cursor = null;
                    ControlA.Cursor = null;
                    Component.Validate.ValidationManager.showMessOnView(this, 10000, strNote, Component.Validate.ValidationManager.MESSEGER_TYPE.ERROR_MESSAGE);
                    break;
                case "THUCHIEN":
                    lblstatus.Foreground = Brushes.Blue;
                    lblstatus.Content = strNote;
                    this.Cursor = System.Windows.Input.Cursors.Wait;
                    ControlA.Cursor = System.Windows.Input.Cursors.Wait;
                    //System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
                    break;
                case "COMPLATE":
                    this.Cursor = null;
                    ControlA.Cursor = null;
                    Component.Validate.ValidationManager.showMessOnView(this, 10000, strNote, Component.Validate.ValidationManager.MESSEGER_TYPE.SUCCESS_MESSAGE);
                    break;
            }
        }

        private void txtGiaTri_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if(txtGiaTri.Text.Trim()=="")
                    {
                        MessageBox.Show("Không có giá trị tìm kiếm!","Thông báo",MessageBoxButton.OK,MessageBoxImage.Warning);
                        return;
                    }
                    else 
                    {
                        ds_BBTHUNGAN.Tables[0].DefaultView.RowFilter = "MA_SOGCS = '" + txtGiaTri.Text.Trim().ToUpper() + "'";
                        if (ds_BBTHUNGAN.Tables[0].DefaultView.Count == 0)
                        {
                            MessageBox.Show("Mã sổ không có giá trị tìm kiếm!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        Find(trvBBAN, txtGiaTri.Text.ToUpper());
                        txtTimKiemTenPTu.Focus();
                    }
                }
            }
            catch
            { }
        }
        private void Find(TreeView mainTreeView, string findToText)
        {
            ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Clear();
            foreach (object item in mainTreeView.Items)
            {
                TreeViewItem tItem = mainTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (tItem != null)
                {
                    //tItem.IsExpanded = true;
                    //isExpand(tItem);
                }
            }
            foreach (object item in mainTreeView.Items)
            {
                TreeViewItem treeItem = mainTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

                if (treeItem != null)
                {
                    //treeItem.IsExpanded = true;
                    FindAll(treeItem, findToText);
                }
                if (item != null)
                {
                    //treeItem.IsExpanded = true;
                    CheckBox chkNode = (CheckBox)treeItem.Header;
                    string[] m = chkNode.Tag.ToString().Split('@');
                    // string obje = treeItem.Header.ToString();
                    if (isContains(chkNode.Content.ToString(), findToText))
                    {
                            chkNode.IsChecked = true;
                            fill_Grid(Convert.ToInt32(m[1].ToString()), m[0].ToString().Trim());
                            // CN_Chamno_ofline f = CN_Chamno_ofline();
                            // f.CheckBox_Click(chkNode,e);
                        
                        //treeItem.Background = Brushes.Red;
                    }
                    else
                    {
                        if (chkNode.IsChecked == true)
                        {
                            chkNode.IsChecked = false;
                        }
                    }
                }
            }
            bodem(ds_HDONCHAMNO);
        }

        void FindAll(ItemsControl items, string findToText)
        {
            //foreach (object ojitem in items.Items)
            //{
            //    ItemsControl ojControl = items.ItemContainerGenerator.ContainerFromItem(ojitem) as ItemsControl;
            //    TreeViewItem ojcitem = ojControl as TreeViewItem;
            //    if (ojcitem != null) ojcitem.IsExpanded = true;
            //}
            foreach (object obj in items.Items)
            {
                ItemsControl childControl = items.ItemContainerGenerator.ContainerFromItem(obj) as ItemsControl;
                if (childControl != null)
                {
                    FindAll(childControl, findToText); // Recursion
                }
                TreeViewItem item = childControl as TreeViewItem;

                if (item != null)
                {
                    //item.IsExpanded = true;
                    CheckBox chkNode = (CheckBox)item.Header;
                    //string a = chkNode.Tag.ToString();
                    string[] m = chkNode.Tag.ToString().Split('@');
                    //item.IsExpanded = true;//only if you dont know type of your Tree (in our case it's A, B or C and you need to use if or switch                        - case statement)                    dynamic obje = item.Header;
                    if (isContains(chkNode.Content.ToString(), findToText))
                    {
                            chkNode.IsChecked = true;
                            fill_Grid(Convert.ToInt32(m[1].ToString()), m[0].ToString().Trim());
                            // CN_Chamno_ofline f = CN_Chamno_ofline;
                            // f.CheckBox_Click(chkNode, e);
                        //item.IsExpanded = true; // if you need to expand and show it
                        //return;
                        //item.Background = Brushes.Red;
                    }
                    else
                    {
                        if (chkNode.IsChecked == true)
                        {
                            chkNode.IsChecked = false;
                        }
                    }
                }
            }
        }
        private bool isContains(string a, string b)
        {
            if (a.ToUpper().Trim() == b.ToUpper().Trim())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void fill_Grid(Int32 sbb, string ma_so)
        {
            // lấy dữ liệu của nút cha
            //clsChamNo_Bus cls = new clsChamNo_Bus();
            dsResult = new DataSet();
            //dsResult = cls.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, sbb, ma_so, "SOGCS", dkien, ref maloi);
            dsResult = GlobalServices.Service_NPCUS.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, sbb, ma_so, "SOGCS", dkien, ref maloi);
            ////
            if (ds_HDONCHAMNO.Tables.Count == 0)
            {
                if (ds_HDONCHAMNO != null)
                {
                    //dsSearch = dsResult.Copy();
                    copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                    ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                    if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                    {
                        dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                    }
                    else
                    { dgrHDON_CNO.ItemsSource = null; }
                }
                else
                { dgrHDON_CNO.ItemsSource = null; }
            }
            else if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count == 0)// chưa có hóa đơn nào
            {   
                //dsSearch = new DataSet();
                if (dsResult != null)
                {
                    //dsSearch = dsResult.Copy();
                    copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                    ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                    if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                    {
                        dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                    }
                    else
                    { dgrHDON_CNO.ItemsSource = null; }
                }
                else
                { dgrHDON_CNO.ItemsSource = null; }
            }
            else
            {
                //copy_dataset(dsResult, dsSearch);
                copy_dataset(dsResult,ds_HDONCHAMNO.Tables["CHAMNO"]);
                ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView.RowFilter = "1=1";
                if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                {
                    dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables["CHAMNO"].DefaultView;
                }
                else
                { dgrHDON_CNO.ItemsSource = null; }
            }
            
            //Decimal Tong_Tiencham = 0;
            //int rowcham = 0;
            //for (int i = 0; i < ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count; i++)
            //{
            //    if (ds_HDONCHAMNO.Tables["CHAMNO"].Rows[i]["CHON"].ToString() == "True")
            //    {
            //        rowcham = rowcham + 1;
            //        Tong_Tiencham = Tong_Tiencham + Convert.ToDecimal(dsSearch.Tables[0].Rows[i]["TIEN_NOP"]) + Convert.ToDecimal(dsSearch.Tables[0].Rows[i]["THUE_NOP"]);
            //    }
            //}
            //lbltonghd_.Content = "Tổng số hóa đơn: " + dsSearch.Tables[0].Rows.Count;
            //lblhdcham_.Content = rowcham.ToString("# ###");
            //lbltongtien_.Content = Tong_Tiencham.ToString("# ### ### ###");

        }
        private void capnhatchamno(string ma_khang,Int64 id_hdon)
        {
            try
            {
                //int Itemrow = dgrHDON_CNO.SelectedIndex;
                //DataRowView drw = null;
                //drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                dt.DefaultView.RowFilter = "MA_KHANG = '" + ma_khang + "' and ID_HDON= '" + id_hdon + "'";
                if (dt.DefaultView.Count == 0) { chamno = false; return; }
                // kiểm tra khách hàng có thu qua ATM;
                //if (cls.check_ATM(dt.DefaultView[0]["MA_KHANG"].ToString(), Convert.ToInt64(dt.DefaultView[0]["ID_HDON"])))
                if(GlobalServices.Service_NPCUS.check_ATM(dt.DefaultView[0]["MA_KHANG"].ToString(), Convert.ToInt64(dt.DefaultView[0]["ID_HDON"])))
                {
                    MessageBox.Show("Khách hàng này đã nộp tiền ATM, hãy kiểm tra lại!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    chamno = false;
                    return;
                }
                //
                ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Clear();
                DataRow dr = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].NewRow();
                //dr["ID_CAYLUOIDIEN"] = OMS_DANHMUC.Pglobal.strMa_dviqly;
                dr["MA_DVIQLY"] = dt.DefaultView[0]["MA_DVIQLY"].ToString();
                dr["MA_KHANG"] = dt.DefaultView[0]["MA_KHANG"].ToString();
                dr["ID_HDON"] = Convert.ToInt64(dt.DefaultView[0]["ID_HDON"]);
                dr["TIEN_NOP"] = Convert.ToDecimal(dt.DefaultView[0]["TIEN_NO"].ToString());
                dr["THUE_NOP"] = Convert.ToDecimal(dt.DefaultView[0]["THUE_NO"].ToString());
                dr["SO_BBGIAO"] = Convert.ToInt64(dt.DefaultView[0]["SO_BBGIAO"]);
                dr["MA_TNGAN"] = strMa_TNgan;
                dr["MA_TNGAN_THUHO"] = dt.DefaultView[0]["MA_TNGAN"].ToString();
                dr["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                dr["NAM_HT"] = nam;
                dr["THANG_HT"] = thang;
                dr["TRANGTHAI"] = 0;
                dr["GROUP_NHOM"] ="";
                dr["NGUOI_TAO"] = strMa_TNgan;
                dr["TINHTRANGIN"] = "0";
                dr["NGAY_TAO"] = DateTime.Now;
                if (chkKhangPthu.IsChecked == true) dr["FMIS"] = "1";
                else dr["FMIS"] = " ";
                ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Add(dr);
                ds_CAPNHAT.AcceptChanges();
                //if (!cls.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                {
                    MessageBox.Show(maloi, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error);
                    //SetStatus("ERORR", Tab_HOADON, maloi);
                    chamno = false;
                    return;
                }
                chamno = true;
                chkKhangPthu.IsChecked = false;
                // ghi log
                GHI_LOG(1);
                decimal sotien = Convert.ToDecimal(dt.DefaultView[0]["TIEN_NO"].ToString()) + Convert.ToDecimal(dt.DefaultView[0]["THUE_NO"].ToString());
                tinhtong("CHAM", sotien);
                // kiểm tra đã nhập đủ thông tin chưa
                
                //
                
            }
            catch
            { }
        }
        private void GHI_LOG(int trangthai)
        {
            try
            {
                //if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                int Itemrow = dgrHDON_CNO.SelectedIndex;
                DataRowView drw = null;
                drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                dt.DefaultView.RowFilter = "MA_KHANG = '" + drw.Row["MA_KHANG"].ToString() + "' and ID_HDON= '" + Convert.ToInt64(drw.Row["ID_HDON"]) + "'";
                if (dt.DefaultView.Count == 0) { chamno = false; return; }
                ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Clear();
                DataRow dr = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].NewRow();
                //dr["ID_CAYLUOIDIEN"] = OMS_DANHMUC.Pglobal.strMa_dviqly;
                dr["MA_DVIQLY"] = dt.DefaultView[0]["MA_DVIQLY"].ToString();
                dr["MA_KHANG"] = dt.DefaultView[0]["MA_KHANG"].ToString();
                dr["ID_HDON"] = Convert.ToInt64(dt.DefaultView[0]["ID_HDON"]);
                dr["SO_BBGIAO"] = Convert.ToInt64(dt.DefaultView[0]["SO_BBGIAO"]);
                dr["NAM_HT"] = nam;
                dr["THANG_HT"] = thang;
                dr["MA_TNGAN"] = strMa_TNgan;
                dr["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                dr["TRANGTHAI"] = trangthai;
                dr["NGUOI_TAO"] = strMa_TNgan;
                dr["NGAY_TAO"] = DateTime.Now;
                dr["GIO"] = DateTime.Now.Hour;
                ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Add(dr);
                ds_CAPNHAT.AcceptChanges();
                //if (!cls.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                {
                    SetStatus("ERORR", Tab_HOADON, maloi);
                    //chamno = false;
                }
            }
            catch
            { }
        }
        private void Huycapnhatchamno(string ma_dviqly,string ma_khang, Int64 id_hdon,int thang, int nam,decimal sotien)
        {
            try
            {
                //if (!cls.delete_NPC_CHAMNO_OFFLINE(ma_dviqly, ma_khang, id_hdon, thang, nam, ref maloi)) 
                if(!GlobalServices.Service_NPCUS.delete_NPC_CHAMNO_OFFLINE(ma_dviqly, ma_khang, id_hdon, thang, nam, ref maloi))
                {
                    SetStatus("ERORR", Tab_HOADON, maloi);
                    chamno = false;
                    return;
                }
                chamno = true;
                GHI_LOG(0);
                //decimal sotien = Convert.ToDecimal(dt.DefaultView[0]["TIEN_NO"].ToString()) + Convert.ToDecimal(dt.DefaultView[0]["THUE_NO"].ToString());
                tinhtong("HUY", sotien);
            }
            catch
            { }
        }
        private void dtpNgayNOP_GotFocus(object sender, RoutedEventArgs e)
        {
            dtpNgayNOP.Background = Brushes.Gold;
        }

        private void dtpNgayNOP_LostFocus(object sender, RoutedEventArgs e)
        {
            dtpNgayNOP.Background = Brushes.Transparent;
        }

        private void txtTimKiemTenPTu_GotFocus(object sender, RoutedEventArgs e)
        {
            txtTimKiemTenPTu.Background = Brushes.Gold;
//            txtTimKiemTenPTu.SelectAll();
        }

        private void txtTimKiemTenPTu_LostFocus(object sender, RoutedEventArgs e)
        {
            txtTimKiemTenPTu.Background = Brushes.Transparent;
        }

        private void txtTimKiemTenPTu_SelectionChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                timkiem = -1;
                
                //if (txtTimKiemTenPTu.Text == forcus_)
                //{
                //    return;
                //}
                //if (ds_HDONCHAMNO.Tables.Count == 0) return;
                //string s = txtTimKiemTenPTu.Text;
                //timkiem = 0;
                //if (s.Trim() == "")
                //{
                //    dgrHDON_CNO.SelectedIndex = 0;
                //    return;
                //}
                //DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"] as DataTable;
                //DataRow[] dr = dt.Select("MA_KHANG LIKE '%" + s.ToUpper() + "%' or TEN_KHANG LIKE '%" + s.ToUpper() + "%' or STT LIKE '%" + s.ToUpper() + "%' or SO_SERY LIKE '%" + s.ToUpper() + "%'", "MA_KHANG,TEN_KHANG,STT,SO_SERY");
                //if (dr.Count() == 0)
                //{
                //    dgrHDON_CNO.SelectedIndex = 0;
                //    return;
                //}
                //else
                //{
                //    for (int i = 0; i < dgrHDON_CNO.Items.Count; i++)
                //    {
                //        DataGridRow row = (DataGridRow)dgrHDON_CNO.ItemContainerGenerator.ContainerFromIndex(i);
                //        TextBlock cellMA_KHANG = dgrHDON_CNO.Columns[2].GetCellContent(row) as TextBlock;
                //        TextBlock cellTEN_KHANG = dgrHDON_CNO.Columns[4].GetCellContent(row) as TextBlock;
                //        TextBlock cellSTT = dgrHDON_CNO.Columns[5].GetCellContent(row) as TextBlock;
                //        TextBlock cellID_HDON = dgrHDON_CNO.Columns[8].GetCellContent(row) as TextBlock;
                //        if (cellMA_KHANG != null && cellTEN_KHANG != null && cellSTT != null && cellID_HDON != null && (cellMA_KHANG.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper()) || cellTEN_KHANG.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper()) || cellSTT.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper()) || cellID_HDON.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper())))
                //        {
                //            object item = dgrHDON_CNO.Items[i];
                //            dgrHDON_CNO.SelectedItem = item;
                //            dgrHDON_CNO.ScrollIntoView(item);
                //            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                //            txtTimKiemTenPTu.Focus();
                //            timkiem = i;
                //            forcus_ = "";
                //            break;
                //        }
                //    }

                //}
            }
            catch
            { }
        }
        private bool checkngayno(Int64 id_hdon)
        {
            try
            {
                DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                dt.DefaultView.RowFilter = "ID_HDON ='" + id_hdon + "'";
                if (TootsNPC.NPCDateTime.ConvertStrToDatime(dt.DefaultView[0]["NGAY_GIAO"].ToString(), "MM/dd/yyyy") > dtpNgayNOP.SelectedDate.Value.Date)
                {
                    MessageBox.Show("Ngày chấm nợ nhỏ hơn ngày giao hóa đơn!", "Cảnh báo", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void txtTimKiemTenPTu_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.F2)
                {
                    if (dkien == 3)
                    {
                        MessageBox.Show("Khách hàng đã được duyệt chấm nợ không thể hủy", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (group == true)
                    {
                        MessageBox.Show("Đang thanh toán tiền cho nhóm khách hàng không thể chấm nợ!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    
                    string s = txtTimKiemTenPTu.Text;
                    if (s.Trim() == "")
                    {
                        txtTimKiemTenPTu.Focus();
                        //e.Handled = true;
                        return;
                    }
                    int Itemrow = dgrHDON_CNO.SelectedIndex;
                    DataRowView drw = null;
                    drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                    // kiểm tra ngày nộp nhỏ hơn ngày giao
                    if(!checkngayno(Convert.ToInt64(drw["ID_HDON"])))
                    {
                        return;
                    }
                    if (drw["CHON"].ToString() == "False")
                    {
                        capnhatchamno(drw["MA_KHANG"].ToString(), Convert.ToInt64(drw["ID_HDON"]));
                        if (chamno == true)
                        {
                            SetStatus("COMPLATE", txtTimKiemTenPTu, "Chấm nợ cho khách hàng: " + drw["TEN_KHANG"].ToString());
                            drw["CHON"] = "True";
                            txtTIENNOP.Text = txtTIENHOADON.Text;
                            drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                        }
                        else
                        { drw["CHON"] = "False"; }
                    }
                    else
                    {
                        drw["CHON"] = "False";
                        txtTIENNOP.Text = "";
                        drw.Row.SetField("TONGNOP", "");
                        Huycapnhatchamno(strMa_dviqly, drw["MA_KHANG"].ToString(), Convert.ToInt64(drw["ID_HDON"]), thang, nam, Convert.ToDecimal(drw.Row["TONGTIEN"].ToString().Replace(" ", "")));
                        SetStatus("COMPLATE", txtTimKiemTenPTu, "Hủy chấm nợ cho khách hàng: " + drw["TEN_KHANG"].ToString());
                    }
                    //bodem(dgrPhanTuDien, lblPtuDien);
                    e.Handled = true;
                    DataGridRow row = (DataGridRow)dgrHDON_CNO.ItemContainerGenerator.ContainerFromIndex(timkiem);
                    object item = dgrHDON_CNO.Items[timkiem];
                    //dgrHDON_CNO.SelectedItem = item;
                    dgrHDON_CNO.ScrollIntoView(item);
                    row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    forcus = true;
                    forcus_ = txtTimKiemTenPTu.Text;
                    txtTimKiemTenPTu.Focus();
                    txtTimKiemTenPTu.SelectAll();
                    bodem(ds_HDONCHAMNO);
                    return;
                }
                if (e.Key == Key.F3) // thực hiện nhóm khách hàng
                {
                    group = true;
                    int DongCuoi = dgrHDON_CNO.Items.Count - 1;
                    int rowindex = dgrHDON_CNO.SelectedIndex;
                    if (rowindex < 0)
                    { SetStatus("COMPLATE", dgrHDON_CNO, "Hãy chọn khách hàng cho vào nhóm"); return; }
                    int Itemrow = dgrHDON_CNO.SelectedIndex;
                    DataRowView drw = null;
                    drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                    DataSet khangnhom = GlobalServices.Service_NPCUS.select_HOADON_NHOM(strMa_dviqly, drw["MA_KHANG"].ToString(), strMa_TNgan);
                    if (khangnhom == null)
                    {
                        khongnhom = false;
                    }
                    else
                    {
                        if (khangnhom.Tables[0].Rows.Count > 0)
                        {
                            khongnhom =true;
                        }
                        else
                        {
                            khongnhom =false;
                        }
                    }
                    if (khongnhom)
                    {
                        nhomthanhtoan = true;
                        drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                        txtTIENNOP.Text = txtTIENHOADON.Text;
                        for (int i = 0; i < khangnhom.Tables[0].Rows.Count; i++)
                        {
                            for (int j = 0; j < ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count; j++)
                            {
                                if (khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString() == ds_HDONCHAMNO.Tables["CHAMNO"].Rows[j]["MA_KHANG"].ToString() && khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString() == ds_HDONCHAMNO.Tables["CHAMNO"].Rows[j]["ID_HDON"].ToString())
                                {
                                    ds_HDONCHAMNO.Tables["CHAMNO"].Rows[j].SetField("CHON", "True");
                                    capnhatchamno(khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString(), Convert.ToInt64(khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString()));
                                    DataTable dtk = ds_HDONCHAMNO.Tables["GROUP"].Copy();
                                    dtk.DefaultView.RowFilter = "MA_KHANG='" + khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString() + "' and ID_HDON ='" + khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString() + "'";
                                    if (dtk.DefaultView.Count > 0)
                                    {
                                        SetStatus("COMPLATE", dgrHDON_CNO, "Khách hàng này đã được chuyển nhóm thanh toán");
                                        //return;
                                    }
                                    else
                                    {
                                        DataTable dtchuyen = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                                        dtchuyen.DefaultView.RowFilter = "MA_KHANG='" + khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString() + "' and ID_HDON ='" + khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString() + "'";
                                        DataRow dr = ds_HDONCHAMNO.Tables["GROUP"].NewRow();
                                        dr["CHON"] = "True";
                                        dr["STT"] = dtchuyen.DefaultView[0]["STT"].ToString();
                                        dr["KYTHANGNAM"] = dtchuyen.DefaultView[0]["KYTHANGNAM"].ToString();
                                        dr["MA_DVIQLY"] = dtchuyen.DefaultView[0]["MA_DVIQLY"].ToString();
                                        dr["MA_KHANG"] = dtchuyen.DefaultView[0]["MA_KHANG"].ToString();
                                        dr["TEN_KHANG"] = dtchuyen.DefaultView[0]["TEN_KHANG"].ToString();
                                        dr["DCHI_KHANG"] = dtchuyen.DefaultView[0]["DCHI_KHANG"].ToString();
                                        dr["MA_SOGCS"] = dtchuyen.DefaultView[0]["MA_SOGCS"].ToString();
                                        dr["TONGTIEN"] = dtchuyen.DefaultView[0]["TONGTIEN"].ToString();
                                        dr["TONGNOP"] = dtchuyen.DefaultView[0]["TONGNOP"].ToString();
                                        dr["TIEN_NO"] = dtchuyen.DefaultView[0]["TIEN_NO"];
                                        dr["THUE_NO"] = dtchuyen.DefaultView[0]["THUE_NO"];
                                        dr["SO_SERY"] = dtchuyen.DefaultView[0]["SO_SERY"];
                                        dr["ID_HDON"] = dtchuyen.DefaultView[0]["ID_HDON"];
                                        dr["SO_BBGIAO"] = dtchuyen.DefaultView[0]["SO_BBGIAO"];
                                        dr["NGAY_GIAO"] = dtchuyen.DefaultView[0]["NGAY_GIAO"];
                                        dr["TRANGTHAI"] = dtchuyen.DefaultView[0]["TRANGTHAI"];
                                        dr["MA_TRAM"] = dtchuyen.DefaultView[0]["MA_TRAM"];
                                        dr["SO_COT"] = dtchuyen.DefaultView[0]["SO_COT"];
                                        dr["SO_HOM"] = dtchuyen.DefaultView[0]["SO_HOM"];
                                        ds_HDONCHAMNO.Tables["GROUP"].Rows.Add(dr);
                                        ds_HDONCHAMNO.AcceptChanges();
                                        dgrGROUP.ItemsSource = ds_HDONCHAMNO.Tables["GROUP"].DefaultView;
                                        dgrGROUP.SelectedIndex = 0;
                                        bodem(ds_HDONCHAMNO);
                                        bodemGROUP(dgrGROUP);
                                    }
                                }
                            }
                        }
                        Tab_NHOM.IsSelected = true;
                        if(dgrGROUP.Items.Count >0) dgrGROUP.SelectedIndex = 0;
                    }
                    else // thuc hien nhom them
                    {
                        if (drw["CHON"].ToString() == "False")
                        {
                            drw["CHON"] = "True";
                            txtTIENNOP.Text = txtTIENHOADON.Text;
                            drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                            capnhatchamno(drw.Row["MA_KHANG"].ToString(), Convert.ToInt64(drw.Row["ID_HDON"]));
                        }
                        DataTable dtk = ds_HDONCHAMNO.Tables["GROUP"].Copy();
                        dtk.DefaultView.RowFilter = "MA_KHANG='" + drw.Row["MA_KHANG"].ToString() + "' and ID_HDON ='" + drw.Row["ID_HDON"].ToString() + "'";
                        if (dtk.DefaultView.Count > 0)
                        {
                            SetStatus("COMPLATE", dgrHDON_CNO, "Khách hàng này đã được chuyển nhóm thanh toán");
                            return;
                        }
                        SetStatus("COMPLATE", dgrHDON_CNO, "Chuyển khách hàng: " + drw["TEN_KHANG"].ToString() + " vào nhóm thanh toán");
                        // kiểm tra xem hóa đơn có được chấm nợ
                        //DataRowView drv = dgrHDON_CNO.SelectedItem as DataRowView;
                        DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                        dt.DefaultView.RowFilter = "MA_KHANG='" + drw.Row["MA_KHANG"].ToString() + "' and ID_HDON ='" + drw.Row["ID_HDON"].ToString() + "'";
                        DataRow dr = ds_HDONCHAMNO.Tables["GROUP"].NewRow();
                        dr["CHON"] = "True";
                        dr["STT"] = dt.DefaultView[0]["STT"].ToString();
                        dr["KYTHANGNAM"] = dt.DefaultView[0]["KYTHANGNAM"].ToString();
                        dr["MA_DVIQLY"] = dt.DefaultView[0]["MA_DVIQLY"].ToString();
                        dr["MA_KHANG"] = dt.DefaultView[0]["MA_KHANG"].ToString();
                        dr["TEN_KHANG"] = dt.DefaultView[0]["TEN_KHANG"].ToString();
                        dr["DCHI_KHANG"] = dt.DefaultView[0]["DCHI_KHANG"].ToString();
                        dr["MA_SOGCS"] = dt.DefaultView[0]["MA_SOGCS"].ToString();
                        dr["TONGTIEN"] = dt.DefaultView[0]["TONGTIEN"].ToString();
                        dr["TONGNOP"] = dt.DefaultView[0]["TONGNOP"].ToString();
                        dr["TIEN_NO"] = dt.DefaultView[0]["TIEN_NO"];
                        dr["THUE_NO"] = dt.DefaultView[0]["THUE_NO"];
                        dr["SO_SERY"] = dt.DefaultView[0]["SO_SERY"];
                        dr["ID_HDON"] = dt.DefaultView[0]["ID_HDON"];
                        dr["SO_BBGIAO"] = dt.DefaultView[0]["SO_BBGIAO"];
                        dr["NGAY_GIAO"] = dt.DefaultView[0]["NGAY_GIAO"];
                        dr["TRANGTHAI"] = dt.DefaultView[0]["TRANGTHAI"];
                        dr["MA_TRAM"] = dt.DefaultView[0]["MA_TRAM"];
                        dr["SO_COT"] = dt.DefaultView[0]["SO_COT"];
                        dr["SO_HOM"] = dt.DefaultView[0]["SO_HOM"];
                        ds_HDONCHAMNO.Tables["GROUP"].Rows.Add(dr);
                        ds_HDONCHAMNO.AcceptChanges();
                        dgrGROUP.ItemsSource = ds_HDONCHAMNO.Tables["GROUP"].DefaultView;
                        dgrGROUP.SelectedIndex = 0;
                        bodem(ds_HDONCHAMNO);
                        bodemGROUP(dgrGROUP);
                    }
                }
                if (e.Key == Key.Enter)
                {
                    
                    if (ds_HDONCHAMNO.Tables.Count == 0) return;
                    string s = txtTimKiemTenPTu.Text;
                    DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"] as DataTable;
                    if (s.Trim() == "")
                    {
                        ds_HDONCHAMNO.Tables[0].DefaultView.RowFilter = "1=1";
                        if (ds_HDONCHAMNO.Tables[0].DefaultView.Count < 200)
                        {
                            dgrHDON_CNO.ItemsSource = ds_HDONCHAMNO.Tables[0].DefaultView;
                        }
                        else
                        { dgrHDON_CNO.ItemsSource = null; }
                        return;
                    }
                    DataRow[] dr = dt.Select("MA_KHANG LIKE '%" + s.ToUpper() + "%' or TEN_KHANG LIKE '%" + s.ToUpper() + "%' or STT LIKE '%" + s.ToUpper() + "%' or SO_SERY LIKE '%" + s.ToUpper() + "%'", "MA_KHANG,TEN_KHANG,STT,SO_SERY");
                    if (dr.Count() == 0)
                    {
                        SetStatus("ERROR", txtTimKiemTenPTu, "Không tìm thấy khách hàng theo điều kiện!");
                        txtTimKiemTenPTu.SelectAll();
                        dgrHDON_CNO.ItemsSource = null;
                        bodem(ds_HDONCHAMNO);
                        // tìm khách hàng tồn tại ở sổ khác
                        if (txtTimKiemTenPTu.Text.Trim().Length == 13)
                        {
                            DataSet ds = new DataSet();
                            //ds = cls.Get_KhachHang(strMa_dviqly, txtTimKiemTenPTu.Text.Trim(),thang,nam,ref messger, ref maloi);
                            ds = GlobalServices.Service_NPCUS.Get_KhachHang(strMa_dviqly, txtTimKiemTenPTu.Text.Trim(), thang, nam, ref messger, ref maloi);
                            if(ds == null )
                            {
                                if (messger !="")
                                {
                                    MessageBox.Show(messger);
                                }
                                else
                                {
                                    MessageBox.Show("Không có khách hàng như giá trị tìm kiếm!");
                                }
                                txtTimKiemTenPTu.Focus();
                                txtTimKiemTenPTu.SelectAll();
                                return;
                            }
                            else
                            {
                                if(ds.Tables[0].Rows.Count == 0)
                                {
                                    if (messger != "")
                                    {
                                        MessageBox.Show(messger);
                                    }
                                    else
                                    {
                                        MessageBox.Show("Không có khách hàng như giá trị tìm kiếm!");
                                    }
                                    txtTimKiemTenPTu.Focus();
                                    txtTimKiemTenPTu.SelectAll();
                                    return;
                                }
                                //hiện thông tin khách hàng
                                if (messger != "1")
                                {
                                    MessageBox.Show(messger);
                                    txtTimKiemTenPTu.Focus();
                                    txtTimKiemTenPTu.SelectAll();
                                    return;
                                }
                                string message = "Mã khách hàng : "+txtTimKiemTenPTu.Text.Trim().ToString() +" Có: " + ds.Tables[0].Rows.Count +" Hóa đơn \r\n";
                                message = message +     "|<><><><><><><><><><><><><><><><><><><><><><><><><><>|" + "\r\n\r\n";
                                for( int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    message = message + "|Hóa đơn " + (i+1).ToString() + ": " + ds.Tables[0].Rows[i]["TEN_KHANG"].ToString() + "     ||     - ID HĐơn:"+ ds.Tables[0].Rows[i]["ID_HDON"].ToString() +"\r\n";
                                    message = message + "|--------------------------------------------------------------------------------------------------" + "\r\n";
                                    message = message + "|Địa chỉ khách hàng: " + ds.Tables[0].Rows[i]["DCHI_KHANG"].ToString() +"\r\n";
                                    message = message + "|--------------------------------------------------------------------------------------------------" + "\r\n";
                                    message = message + "|Kỳ-Tháng/Năm:  " + ds.Tables[0].Rows[i]["KYTHANGNAM"].ToString() +" \r\n";
                                    message = message + "|--------------------------------------------------------------------------------------------------" + "\r\n";
                                    message = message + "|Số biên bản giao: " + ds.Tables[0].Rows[i]["SO_BBGIAO"].ToString() + "    ||    - Mã sổ GCS: " + ds.Tables[0].Rows[i]["MA_SOGCS"].ToString() + "\r\n";
                                    message = message + "|--------------------------------------------------------------------------------------------------" + "\r\n";
                                    message = message + "|Được giao cho TNV: " + ds.Tables[0].Rows[i]["MA_TNGAN"].ToString() + " - "+ ds.Tables[0].Rows[i]["TEN_TNGAN"].ToString() +"\r\n";
                                    message = message + "|--------------------------------------------------------------------------------------------------" + "\r\n";
                                    message = message + "|Ngày giao: " + ds.Tables[0].Rows[i]["NGAY_GIAO"].ToString() +"\r\n";
                                    message = message + "|--------------------------------------------------------------------------------------------------" + "\r\n";
                                    message = message + "|Tổng tiền giao: " + ds.Tables[0].Rows[i]["TONGTIENPS"].ToString() +  " VNĐ    ||    - Tổng tiền Nợ: " + ds.Tables[0].Rows[i]["TONGTIENNO"].ToString() +" VNĐ\r\n";
                                    message = message + "|====================================================" + "|\r\n\r\n";
                                }
                                MessageBox.Show(message, "Thông tin khách hàng");
                                txtTimKiemTenPTu.Focus();
                                txtTimKiemTenPTu.SelectAll();
                            }

                        }
                        return;
                    }
                    else
                    {
                        DataTable dtt = new DataTable();
                        //dtt = dt.Select("MA_KHANG LIKE '%" + s.ToUpper() + "%' or TEN_KHANG LIKE '%" + s.ToUpper() + "%' or STT LIKE '%" + s.ToUpper() + "%' or SO_SERY LIKE '%" + s.ToUpper() + "%'", "MA_KHANG,TEN_KHANG,STT,SO_SERY").CopyToDataTable();
                        dt.DefaultView.RowFilter ="MA_KHANG LIKE '%" + s.ToUpper() + "%' or TEN_KHANG LIKE '%" + s.ToUpper() + "%' or STT LIKE '%" + s.ToUpper() + "%' or SO_SERY LIKE '%" + s.ToUpper() + "%'";
                        dgrHDON_CNO.ItemsSource = dt.DefaultView;
                        dgrHDON_CNO.SelectedIndex = 0;
                        bodem(ds_HDONCHAMNO);
                        txtTimKiemTenPTu.SelectAll();
                        //for (int i = timkiem + 1; i < dgrHDON_CNO.Items.Count; i++)
                        //{
                        //    DataGridRow row = (DataGridRow)dgrHDON_CNO.ItemContainerGenerator.ContainerFromIndex(i);
                        //    TextBlock cellMA_KHANG = dgrHDON_CNO.Columns[2].GetCellContent(row) as TextBlock;
                        //    TextBlock cellTEN_KHANG = dgrHDON_CNO.Columns[4].GetCellContent(row) as TextBlock;
                        //    TextBlock cellSTT = dgrHDON_CNO.Columns[5].GetCellContent(row) as TextBlock;
                        //    TextBlock cellID_HDON = dgrHDON_CNO.Columns[8].GetCellContent(row) as TextBlock;
                        //    if (cellMA_KHANG != null && cellTEN_KHANG != null && cellSTT != null && cellID_HDON != null && (cellMA_KHANG.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper()) || cellTEN_KHANG.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper()) || cellSTT.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper()) || cellID_HDON.Text.ToUpper().Contains(txtTimKiemTenPTu.Text.ToUpper())))
                        //    {
                        //        object item = dgrHDON_CNO.Items[i];
                        //        dgrHDON_CNO.SelectedItem = item;
                        //        dgrHDON_CNO.ScrollIntoView(item);
                        //        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                        //        txtTimKiemTenPTu.Focus();
                        //        timkiem = i;
                        //        if (i == dgrHDON_CNO.Items.Count - 1) timkiem = 0;
                        //        break;
                        //    }
                        //    if (i == dgrHDON_CNO.Items.Count - 1) timkiem = 0;
                        //}

                    }
                }
            }
            catch
            { }
        }
        private void bodem(DataSet ds)
        {
            //txtTONGTIENGIAO.Text = tongTienGiao.ToString("# ### ### ###");
            //txtTONGTIENNOP.Text = tongTienNop.ToString("# ### ### ###");
            //txtTONGTIENNO.Text = tongTienNo.ToString("# ### ### ###");
            lblTongso.Content = "Tổng số: " + ds.Tables["CHAMNO"].Rows.Count.ToString();
        }
        private void bodemGROUP(DataGrid dg)
        {
            DataRowView drw = null;
            int dem = 0;
            Decimal tongTienGiao = 0;
            for (int i = 0; i <= dg.Items.Count - 1; i++)
            {
                drw = (DataRowView)dg.Items[i];
                tongTienGiao = tongTienGiao + Convert.ToDecimal(drw["TIEN_NO"]) + Convert.ToDecimal(drw["THUE_NO"]);
            }
            txtTONGTIENGIAO_GROUP.Text = tongTienGiao.ToString("# ### ### ###");
            txtTONGTIENNOP_GROUP.Text = tongTienGiao.ToString("# ### ### ###");
            txtTIENTRALAI_GROUP.Text = "0";
            lblTONGSO_GROUP.Content = "Tổng số: " + dg.Items.Count.ToString();
        }
        private void dgrHDON_CNO_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                int DongCuoi = dgrHDON_CNO.Items.Count - 1;
                int rowindex = dgrHDON_CNO.SelectedIndex;
                if (rowindex < 0)
                { //Xoa_text(); 
                    return; }
                DataRowView drv = dgrHDON_CNO.SelectedItem as DataRowView;
                DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                dt.DefaultView.RowFilter = "MA_KHANG='" + drv.Row["MA_KHANG"].ToString() + "' and ID_HDON ='" + drv.Row["ID_HDON"].ToString() + "'";
                txtMA_KHANG.Text = dt.DefaultView[0]["MA_KHANG"].ToString();
                txtTEN_KHANG.Text = dt.DefaultView[0]["TEN_KHANG"].ToString();
                txtDCHI_KHANG.Text = dt.DefaultView[0]["DCHI_KHANG"].ToString();
                txtSO_SERY.Text = dt.DefaultView[0]["SO_SERY"].ToString();
                txtMA_SOGCS.Text = dt.DefaultView[0]["MA_SOGCS"].ToString();
                txtSTT.Text = dt.DefaultView[0]["STT"].ToString();
                
                txtTIENHOADON.Text = dt.DefaultView[0]["TONGTIEN"].ToString();
                txtTIENTRALAI.Text = "0";
                //txtTimKiemTenPTu.Text = "";
                //lblTongso.Content = "Tổng số 0/0";
                //txtTIENHOADON.Text = (Convert.ToDecimal(dt.DefaultView[0]["TIEN_NO"]) + Convert.ToDecimal(dt.DefaultView[0]["THUE_NO"])).ToString("# ### ### ###");
                    if (dt.DefaultView[0]["TONGNOP"].ToString().Trim() == "")
                    {
                        txtTIENNOP.Text ="";
                    }
                    else
                    {
                        txtTIENNOP.Text = dt.DefaultView[0]["TONGNOP"].ToString();
                    }
                    txtMA_TRAM.Text = dt.DefaultView[0]["MA_TRAM"].ToString();
                    txtSO_COT.Text = dt.DefaultView[0]["SO_COT"].ToString();
                    txtSO_HOM.Text = dt.DefaultView[0]["SO_HOM"].ToString();
                //// gán mã trạm
                //    DataSet ds = new DataSet();
                //    ds = cls.select_MATRAM(strMa_dviqly, dt.DefaultView[0]["MA_KHANG"].ToString());
                //    txtMA_TRAM.Text ="";
                //    txtSO_COT.Text = "";
                //    txtSO_HOM.Text = "";
                //    if (ds.Tables.Count == 0) return;
                //    for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++)
                //    {
                //        txtMA_TRAM.Text = txtMA_TRAM.Text + ds.Tables[0].Rows[i]["MA_TRAM"].ToString() + ";";
                //        txtSO_COT.Text = txtSO_COT.Text + ds.Tables[0].Rows[i]["SO_COT"].ToString() + ";";
                //        txtSO_HOM.Text = txtSO_HOM.Text + ds.Tables[0].Rows[i]["SO_HOM"].ToString() + ";";
                //    }
            }
            catch
            {}
        }

        private void CHECK_HOADON_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                DataRowView drv = dgrHDON_CNO.SelectedItem as DataRowView;
                int tong = 0;
                Decimal tongtien = 0;
                if (group == true)
                {
                    MessageBox.Show("Đang thanh toán tiền cho nhóm khách hàng không thể chấm nợ!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    if (chk.IsChecked == true)
                    { chk.IsChecked = false; return; }
                    if (chk.IsChecked == false)
                    { chk.IsChecked = true; return; }
                }
                if (dkien == 3)
                {
                    MessageBox.Show("Khách hàng đã được duyệt chấm nợ không thể hủy!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    chk.IsChecked = true;
                    return; 
                }
                if (chk.IsChecked == true)
                {
                    //txtTIENNOP.Text = txtTIENHOADON.Text;
                    //drv.Row.SetField("TIEN_NOP", drv.Row["TIEN_NO"].ToString());
                    //drv.Row.SetField("THUE_NOP", drv.Row["THUE_NO"].ToString());
                    //tongtien = Convert.ToDecimal(lblTONGSOTIEN_DACHAM.Content.ToString()) + Convert.ToDecimal(drv.Row["TIEN_NO"]) + Convert.ToDecimal(drv.Row["TIEN_NO"]);
                    //tong = Convert.ToInt32(lblTONGSOHDON_DACHAM.Content.ToString()) + 1;
                    capnhatchamno(drv["MA_KHANG"].ToString(), Convert.ToInt64(drv["ID_HDON"]));
                    if (chamno)
                    {
                        drv.Row.SetField("TONGNOP", drv.Row["TONGTIEN"].ToString());
                        SetStatus("COMPLATE", txtTimKiemTenPTu, "Chấm nợ cho khách hàng: " + drv["TEN_KHANG"].ToString());
                        txtTIENNOP.Focus();
                    }
                    else chk.IsChecked = false;
                }
                else
                {
                    //DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                    //dt.DefaultView.RowFilter = "MA_DVIQLY = '" + HETHONGCHAMNO.Pglobal.strMa_dviqly + "' and ID_HDON = '" + Convert.ToInt64(drv.Row["ID_HDON"]) + "'";
                    //if (dt.DefaultView[0]["TRANGTHAI"].ToString() == "1")
                    //{
                    //    MessageBox.Show("Hóa đơn đã xuất file ko thể hủy chấm nợ!", "Cảnh báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    //    drv.Row.SetField("CHON", "True");
                    //    return;
                    //}
                    txtTIENNOP.Text = "";
                    //drv.Row.SetField("TIEN_NOP", Decimal.Zero);
                    //drv.Row.SetField("THUE_NOP", Decimal.Zero);
                    drv.Row.SetField("TONGNOP", "");
                    //tongtien = Convert.ToDecimal(lblTONGSOTIEN_DACHAM.Content.ToString()) - Convert.ToDecimal(drv.Row["TIEN_NO"]) - Convert.ToDecimal(drv.Row["TIEN_NO"]);
                    //tong = Convert.ToInt32(lblTONGSOHDON_DACHAM.Content.ToString()) - 1;
                    Huycapnhatchamno(strMa_dviqly, drv["MA_KHANG"].ToString(), Convert.ToInt64(drv["ID_HDON"]), thang, nam, Convert.ToDecimal(drv.Row["TONGTIEN"].ToString().Replace(" ","")));
                    if (chamno) SetStatus("COMPLATE", txtTimKiemTenPTu, "Hủy chấm nợ cho khách hàng: " + drv["TEN_KHANG"].ToString());
                }
                //lblTONGSOHDON_DACHAM.Content = tong.ToString();
                //lblTONGSOTIEN_DACHAM.Content = tongtien.ToString("#,###,###,###.##");
                bodem(ds_HDONCHAMNO);
            }
            catch
            { }
        }
        private void tinhtong(string tthai,decimal sotien)
        {
            try
            {
                decimal tongtien = Convert.ToDecimal(txtTONGTIENGIAO.Text.Replace(" ", "").ToString());
                decimal tongtiennop = Convert.ToDecimal(txtTONGTIENNOP.Text.Replace(" ", "").ToString());
                decimal tongtienno;
                if (tthai == "CHAM")
                {
                    tongtiennop = tongtiennop + sotien;
                    tongtienno = tongtien - tongtiennop;
                    txtTONGTIENNOP.Text = tongtiennop.ToString("# ### ### ###");
                    txtTONGTIENNO.Text = tongtienno.ToString("# ### ### ###");
                }
                if (tthai == "HUY")
                {
                    tongtiennop = tongtiennop - sotien;
                    tongtienno = tongtien - tongtiennop;
                    txtTONGTIENNOP.Text = tongtiennop.ToString("# ### ### ###");
                    txtTONGTIENNO.Text = tongtienno.ToString("# ### ### ###");
                }
            }
            catch
            {}
        }
        private void txtTIENNOP_GotFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                txtTIENNOP.Background = Brushes.Gold;
                txtTIENNOP.Text = "";
                //txtTIENNOP.Text = Convert.ToDecimal(format_laitexttheodinhdang(txtTIENNOP.Text)).ToString("#,###,###,###");
                txtTIENNOP.SelectAll();
            }
            catch
            { }
        }

        private void txtTIENNOP_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtTIENNOP.Text.Trim() == "") return;
                txtTIENNOP.Text = Convert.ToDecimal(txtTIENNOP.Text).ToString("# ### ### ###");
                txtTIENNOP.Background = Brushes.Transparent;
            }
            catch
            { }
        }
        private string format_laitexttheodinhdang(string text) //"######.##"
        {
            if (text.Trim().ToString() == "")
            {
                return "0";
            }
            string a = text.Trim().Replace(' ', ',');
            return a;
        }

        
        private void huy_rowchamno()
        {
            try
            {
                DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"] as DataTable;
                DataRowView drw = null;
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    if (dt.Rows[i]["CHON"].ToString() == "True")
                    {
                        // hủy thanh toán tiền trước;
                        dt.Rows.RemoveAt(i);
                    }
                }
                for (int i = dgrHDON_CNO.Items.Count - 1; i >=0 ; i--)
                {
                    drw = (DataRowView)dgrHDON_CNO.Items[i];
                    if (drw["CHON"].ToString() == "True")
                    {
                        drw.Delete();
                    }
                }
            }
            catch
            { }
        }
        private void dgrHDON_CNO_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int Itemrow = dgrHDON_CNO.SelectedIndex;
                DataRowView drw = null;
                drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                if (Itemrow < 0) return;
                if (e.Key == Key.F2)
                {
                    if (dkien == 3)
                    {
                        MessageBox.Show("Khách hàng đã được duyệt chấm nợ không thể hủy", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (group == true)
                    {
                        MessageBox.Show("Đang thanh toán tiền cho nhóm khách hàng không thể chấm nợ!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    string s = txtTimKiemTenPTu.Text;
                    if (s.Trim() == "")
                    {
                        txtTimKiemTenPTu.Focus();
                        //e.Handled = true;
                        return;
                    }
                    drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                    // kiểm tra ngày nộp nhỏ hơn ngày giao
                    if (!checkngayno(Convert.ToInt64(drw["ID_HDON"])))
                    {
                        return;
                    }
                    if (drw["CHON"].ToString() == "False")
                    {
                        capnhatchamno(drw["MA_KHANG"].ToString(), Convert.ToInt64(drw["ID_HDON"]));
                        if (chamno == true)
                        {
                            SetStatus("COMPLATE", txtTimKiemTenPTu, "Chấm nợ cho khách hàng: " + drw["TEN_KHANG"].ToString());
                            drw["CHON"] = "True";
                            txtTIENNOP.Text = txtTIENHOADON.Text;
                            drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                        }
                        else
                        { drw["CHON"] = "False"; }
                    }
                    else
                    {
                        drw["CHON"] = "False";
                        txtTIENNOP.Text = "";
                        drw.Row.SetField("TONGNOP", "");
                        Huycapnhatchamno(strMa_dviqly, drw["MA_KHANG"].ToString(), Convert.ToInt64(drw["ID_HDON"]), thang, nam, Convert.ToDecimal(drw.Row["TONGTIEN"].ToString().Replace(" ","")));
                        SetStatus("COMPLATE", txtTimKiemTenPTu, "Hủy chấm nợ cho khách hàng: " + drw["TEN_KHANG"].ToString());
                    }
                    //bodem(dgrPhanTuDien, lblPtuDien);
                    e.Handled = true;
                    DataGridRow row = (DataGridRow)dgrHDON_CNO.ItemContainerGenerator.ContainerFromIndex(timkiem);
                    object item = dgrHDON_CNO.Items[timkiem];
                    //dgrHDON_CNO.SelectedItem = item;
                    dgrHDON_CNO.ScrollIntoView(item);
                    row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    forcus = true;
                    forcus_ = txtTimKiemTenPTu.Text;
                    txtTimKiemTenPTu.Focus();
                    txtTimKiemTenPTu.SelectAll();
                    bodem(ds_HDONCHAMNO);
                    return;
                }
                if (e.Key == Key.F3) // thực hiện nhóm khách hàng
                {
                    group = true;
                    int DongCuoi = dgrHDON_CNO.Items.Count - 1;
                    int rowindex = dgrHDON_CNO.SelectedIndex;
                    if (rowindex < 0)
                    { SetStatus("COMPLATE", dgrHDON_CNO, "Hãy chọn khách hàng cho vào nhóm"); return; }
                    DataSet khangnhom = GlobalServices.Service_NPCUS.select_HOADON_NHOM(strMa_dviqly, drw["MA_KHANG"].ToString(), strMa_TNgan);
                    if (khangnhom == null)
                    {
                        khongnhom = false;
                    }
                    else
                    {
                        if (khangnhom.Tables[0].Rows.Count > 0)
                        {
                            khongnhom =true;
                        }
                        else
                        {
                            khongnhom =false;
                        }
                    }
                    if (khongnhom)
                    {
                        nhomthanhtoan = true;
                        drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                        txtTIENNOP.Text = txtTIENHOADON.Text;
                        for (int i = 0; i < khangnhom.Tables[0].Rows.Count; i++)
                        {
                            for (int j = 0; j < ds_HDONCHAMNO.Tables["CHAMNO"].Rows.Count; j++)
                            {
                                if (khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString() == ds_HDONCHAMNO.Tables["CHAMNO"].Rows[j]["MA_KHANG"].ToString() && khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString() == ds_HDONCHAMNO.Tables["CHAMNO"].Rows[j]["ID_HDON"].ToString())
                                {
                                    ds_HDONCHAMNO.Tables["CHAMNO"].Rows[j].SetField("CHON", "True");
                                    capnhatchamno(khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString(), Convert.ToInt64(khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString()));
                                    DataTable dtk = ds_HDONCHAMNO.Tables["GROUP"].Copy();
                                    dtk.DefaultView.RowFilter = "MA_KHANG='" + khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString() + "' and ID_HDON ='" + khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString() + "'";
                                    if (dtk.DefaultView.Count > 0)
                                    {
                                        SetStatus("COMPLATE", dgrHDON_CNO, "Khách hàng này đã được chuyển nhóm thanh toán");
                                        //return;
                                    }
                                    else
                                    {
                                        DataTable dtchuyen = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                                        dtchuyen.DefaultView.RowFilter = "MA_KHANG='" + khangnhom.Tables[0].Rows[i]["MA_KHANG"].ToString() + "' and ID_HDON ='" + khangnhom.Tables[0].Rows[i]["ID_HDON"].ToString() + "'";
                                        DataRow dr = ds_HDONCHAMNO.Tables["GROUP"].NewRow();
                                        dr["CHON"] = "True";
                                        dr["STT"] = dtchuyen.DefaultView[0]["STT"].ToString();
                                        dr["KYTHANGNAM"] = dtchuyen.DefaultView[0]["KYTHANGNAM"].ToString();
                                        dr["MA_DVIQLY"] = dtchuyen.DefaultView[0]["MA_DVIQLY"].ToString();
                                        dr["MA_KHANG"] = dtchuyen.DefaultView[0]["MA_KHANG"].ToString();
                                        dr["TEN_KHANG"] = dtchuyen.DefaultView[0]["TEN_KHANG"].ToString();
                                        dr["DCHI_KHANG"] = dtchuyen.DefaultView[0]["DCHI_KHANG"].ToString();
                                        dr["MA_SOGCS"] = dtchuyen.DefaultView[0]["MA_SOGCS"].ToString();
                                        dr["TONGTIEN"] = dtchuyen.DefaultView[0]["TONGTIEN"].ToString();
                                        dr["TONGNOP"] = dtchuyen.DefaultView[0]["TONGNOP"].ToString();
                                        dr["TIEN_NO"] = dtchuyen.DefaultView[0]["TIEN_NO"];
                                        dr["THUE_NO"] = dtchuyen.DefaultView[0]["THUE_NO"];
                                        dr["SO_SERY"] = dtchuyen.DefaultView[0]["SO_SERY"];
                                        dr["ID_HDON"] = dtchuyen.DefaultView[0]["ID_HDON"];
                                        dr["SO_BBGIAO"] = dtchuyen.DefaultView[0]["SO_BBGIAO"];
                                        dr["NGAY_GIAO"] = dtchuyen.DefaultView[0]["NGAY_GIAO"];
                                        dr["TRANGTHAI"] = dtchuyen.DefaultView[0]["TRANGTHAI"];
                                        dr["MA_TRAM"] = dtchuyen.DefaultView[0]["MA_TRAM"];
                                        dr["SO_COT"] = dtchuyen.DefaultView[0]["SO_COT"];
                                        dr["SO_HOM"] = dtchuyen.DefaultView[0]["SO_HOM"];
                                        ds_HDONCHAMNO.Tables["GROUP"].Rows.Add(dr);
                                        ds_HDONCHAMNO.AcceptChanges();
                                        dgrGROUP.ItemsSource = ds_HDONCHAMNO.Tables["GROUP"].DefaultView;
                                        dgrGROUP.SelectedIndex = 0;
                                        bodem(ds_HDONCHAMNO);
                                        bodemGROUP(dgrGROUP);
                                    }
                                }
                            }
                        }
                        Tab_NHOM.IsSelected = true;
                        if (dgrGROUP.Items.Count > 0) dgrGROUP.SelectedIndex = 0;
                    }
                    else // thuc hien nhom them
                    {
                        if (drw["CHON"].ToString() == "False")
                        {
                            drw["CHON"] = "True";
                            txtTIENNOP.Text = txtTIENHOADON.Text;
                            drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                            capnhatchamno(drw.Row["MA_KHANG"].ToString(), Convert.ToInt64(drw.Row["ID_HDON"]));
                        }
                        DataTable dtk = ds_HDONCHAMNO.Tables["GROUP"].Copy();
                        dtk.DefaultView.RowFilter = "MA_KHANG='" + drw.Row["MA_KHANG"].ToString() + "' and ID_HDON ='" + drw.Row["ID_HDON"].ToString() + "'";
                        if (dtk.DefaultView.Count > 0)
                        {
                            SetStatus("COMPLATE", dgrHDON_CNO, "Khách hàng này đã được chuyển nhóm thanh toán");
                            return;
                        }
                        SetStatus("COMPLATE", dgrHDON_CNO, "Chuyển khách hàng: " + drw["TEN_KHANG"].ToString() + " vào nhóm thanh toán");
                        // kiểm tra xem hóa đơn có được chấm nợ
                        //DataRowView drv = dgrHDON_CNO.SelectedItem as DataRowView;
                        DataTable dt = ds_HDONCHAMNO.Tables["CHAMNO"].Copy();
                        dt.DefaultView.RowFilter = "MA_KHANG='" + drw.Row["MA_KHANG"].ToString() + "' and ID_HDON ='" + drw.Row["ID_HDON"].ToString() + "'";
                        DataRow dr = ds_HDONCHAMNO.Tables["GROUP"].NewRow();
                        dr["CHON"] = "True";
                        dr["STT"] = dt.DefaultView[0]["STT"].ToString();
                        dr["KYTHANGNAM"] = dt.DefaultView[0]["KYTHANGNAM"].ToString();
                        dr["MA_DVIQLY"] = dt.DefaultView[0]["MA_DVIQLY"].ToString();
                        dr["MA_KHANG"] = dt.DefaultView[0]["MA_KHANG"].ToString();
                        dr["TEN_KHANG"] = dt.DefaultView[0]["TEN_KHANG"].ToString();
                        dr["DCHI_KHANG"] = dt.DefaultView[0]["DCHI_KHANG"].ToString();
                        dr["MA_SOGCS"] = dt.DefaultView[0]["MA_SOGCS"].ToString();
                        dr["TONGTIEN"] = dt.DefaultView[0]["TONGTIEN"].ToString();
                        dr["TONGNOP"] = dt.DefaultView[0]["TONGNOP"].ToString();
                        dr["TIEN_NO"] = dt.DefaultView[0]["TIEN_NO"];
                        dr["THUE_NO"] = dt.DefaultView[0]["THUE_NO"];
                        dr["SO_SERY"] = dt.DefaultView[0]["SO_SERY"];
                        dr["ID_HDON"] = dt.DefaultView[0]["ID_HDON"];
                        dr["SO_BBGIAO"] = dt.DefaultView[0]["SO_BBGIAO"];
                        dr["NGAY_GIAO"] = dt.DefaultView[0]["NGAY_GIAO"];
                        dr["TRANGTHAI"] = dt.DefaultView[0]["TRANGTHAI"];
                        dr["MA_TRAM"] = dt.DefaultView[0]["MA_TRAM"];
                        dr["SO_COT"] = dt.DefaultView[0]["SO_COT"];
                        dr["SO_HOM"] = dt.DefaultView[0]["SO_HOM"];
                        ds_HDONCHAMNO.Tables["GROUP"].Rows.Add(dr);
                        ds_HDONCHAMNO.AcceptChanges();
                        dgrGROUP.ItemsSource = ds_HDONCHAMNO.Tables["GROUP"].DefaultView;
                        dgrGROUP.SelectedIndex = 0;
                        bodem(ds_HDONCHAMNO);
                        bodemGROUP(dgrGROUP);
                    }
                }
            }
            catch
            { }
        }

        private void dgrGROUP_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                int DongCuoi = dgrGROUP.Items.Count - 1;
                int rowindex = dgrGROUP.SelectedIndex;
                if (rowindex < 0)
                { dgrGROUP.ItemsSource = null; Xoa_text(); txtTEN_KHANG_GROUP.Text = ""; return; }
                DataRowView drv = dgrGROUP.SelectedItem as DataRowView;
                DataTable dt = ds_HDONCHAMNO.Tables["GROUP"].Copy();
                dt.DefaultView.RowFilter = "MA_KHANG='" + drv.Row["MA_KHANG"].ToString() + "' and ID_HDON ='" + drv.Row["ID_HDON"].ToString() + "'";
                txtMA_KHANG.Text = dt.DefaultView[0]["MA_KHANG"].ToString();
                txtTEN_KHANG.Text = dt.DefaultView[0]["TEN_KHANG"].ToString();
                txtTEN_KHANG_GROUP.Text = dt.DefaultView[0]["TEN_KHANG"].ToString();
                txtDCHI_KHANG.Text = dt.DefaultView[0]["DCHI_sKHANG"].ToString();
                txtSO_SERY.Text = dt.DefaultView[0]["SO_SERY"].ToString();
                txtMA_SOGCS.Text = dt.DefaultView[0]["MA_SOGCS"].ToString();
                txtSTT.Text = dt.DefaultView[0]["STT"].ToString();
                //txtTIENHOADON.Text = dt.DefaultView[0]["TONGTIEN"].ToString();
                //txtTIENTRALAI.Text = "0";
                //txtTimKiemTenPTu.Text = "";
                //lblTongso.Content = "Tổng số 0/0";
                //txtTIENHOADON.Text = (Convert.ToDecimal(dt.DefaultView[0]["TIEN_NO"]) + Convert.ToDecimal(dt.DefaultView[0]["THUE_NO"])).ToString("# ### ### ###");
               
                txtMA_TRAM.Text = dt.DefaultView[0]["MA_TRAM"].ToString();
                txtSO_COT.Text = dt.DefaultView[0]["SO_COT"].ToString();
                txtSO_HOM.Text = dt.DefaultView[0]["SO_HOM"].ToString();
                //// gán mã trạm
                //    DataSet ds = new DataSet();
                //    ds = cls.select_MATRAM(strMa_dviqly, dt.DefaultView[0]["MA_KHANG"].ToString());
                //    txtMA_TRAM.Text ="";
                //    txtSO_COT.Text = "";
                //    txtSO_HOM.Text = "";
                //    if (ds.Tables.Count == 0) return;
                //    for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++)
                //    {
                //        txtMA_TRAM.Text = txtMA_TRAM.Text + ds.Tables[0].Rows[i]["MA_TRAM"].ToString() + ";";
                //        txtSO_COT.Text = txtSO_COT.Text + ds.Tables[0].Rows[i]["SO_COT"].ToString() + ";";
                //        txtSO_HOM.Text = txtSO_HOM.Text + ds.Tables[0].Rows[i]["SO_HOM"].ToString() + ";";
                //    }
            }
            catch
            { }
        }

        private void txtTONGTIENNOP_GROUP_GotFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                txtTONGTIENNOP_GROUP.Background = Brushes.Gold;
                txtTONGTIENNOP_GROUP.Text = "";
                //txtTONGTIENNOP_GROUP.Text = Convert.ToDecimal(format_laitexttheodinhdang(txtTONGTIENNOP_GROUP.Text)).ToString("###");
                txtTONGTIENNOP_GROUP.SelectAll();
            }
            catch { }
        }

        private void txtTONGTIENNOP_GROUP_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtTONGTIENNOP_GROUP.Text.Trim() == "") return;
                txtTONGTIENNOP_GROUP.Text = Convert.ToDecimal(txtTONGTIENNOP_GROUP.Text).ToString("# ### ### ###");
                txtTONGTIENNOP_GROUP.Background = Brushes.Transparent;
            }
            catch { }
        }

        private void tabctr_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (Tab_HOADON.IsSelected)
                {
                    lblFFF.Content = "(F2: chấm nợ; F3: nhóm khách hàng;";
                }
                else
                {
                    lblFFF.Content = "Ctrl + S: Cập nhật nhóm";
                }
                
            }
            catch { }
        }

        private void CHECK_GROUP_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                DataRowView drv = dgrGROUP.SelectedItem as DataRowView;
                
                SetStatus("COMPLATE", txtTimKiemTenPTu, "Hủy nhóm khách hàng: " + drv["TEN_KHANG"].ToString());
                int tong = 0;
                Decimal tongtien = 0;
                if (chk.IsChecked == false)
                {
                    DataTable dt = ds_HDONCHAMNO.Tables["GROUP"] as DataTable;
                    for (int i = dt.Rows.Count - 1; i >= 0; i--)
                    {
                        if (dt.Rows[i]["CHON"].ToString() == "False")
                        { 
                            // hủy thanh toán tiền trước;
                            Huycapnhatchamno(strMa_dviqly, dt.Rows[i]["MA_KHANG"].ToString(), Convert.ToInt64(dt.Rows[i]["ID_HDON"]), thang, nam, Convert.ToDecimal(dt.Rows[i]["TONGTIEN"]));
                            for (int j = 0; j < dgrHDON_CNO.Items.Count; j++)
                            {
                                dgrHDON_CNO.SelectedIndex = j;
                                DataRowView drv1 = dgrHDON_CNO.SelectedItem as DataRowView;
                                if (Convert.ToInt64(dt.Rows[i]["ID_HDON"]) == Convert.ToInt64(drv1["ID_HDON"]))
                                {
                                    drv1["CHON"] = "False";
                                }
                            }
                            dt.Rows.RemoveAt(i); }
                    }
                    dgrGROUP.ItemsSource = ds_HDONCHAMNO.Tables["GROUP"].DefaultView;
                    bodemGROUP(dgrGROUP);
                }
            }
            catch
            { }
        }

        private void tabctr_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int Itemrow = dgrHDON_CNO.SelectedIndex;
                DataRowView drw = null;
                drw = (DataRowView)dgrHDON_CNO.Items[Itemrow];
                if (Itemrow < 0) return;
                if (Tab_HOADON.IsSelected)
                {
                    if (e.Key == Key.F2)
                    {
                        if (group == true)
                        {
                            MessageBox.Show("Đang thanh toán tiền cho nhóm khách hàng không thể chấm nợ!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        if (dkien == 3)
                        {
                            MessageBox.Show("Khách hàng đã được duyệt chấm nợ không thể hủy", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        if (drw["CHON"].ToString() == "False")
                        {
                            drw["CHON"] = "True";
                            txtTIENNOP.Text = txtTIENHOADON.Text;
                            drw.Row.SetField("TONGNOP", drw.Row["TONGTIEN"].ToString());
                            capnhatchamno(drw["MA_KHANG"].ToString(), Convert.ToInt64(drw["ID_HDON"]));
                            if (chamno)
                            {
                                txtTIENNOP.Focus();
                                SetStatus("COMPLATE", dgrHDON_CNO, "Chấm nợ cho khách hàng: " + drw["TEN_KHANG"].ToString());
                            }
                        }
                        else
                        {
                            drw["CHON"] = "False";
                            txtTIENNOP.Text = "";
                            drw.Row.SetField("TONGNOP", "");
                            Huycapnhatchamno(strMa_dviqly, drw["MA_KHANG"].ToString(), Convert.ToInt64(drw["ID_HDON"]), thang, nam, Convert.ToDecimal(drw["TONGTIEN"].ToString().Replace(" ","")));
                            if (chamno) SetStatus("COMPLATE", txtTimKiemTenPTu, "Hủy chấm nợ cho khách hàng: " + drw["TEN_KHANG"].ToString());
                        }
                        bodem(ds_HDONCHAMNO);
                        return;
                    }
                }
                if (Tab_NHOM.IsSelected)
                {
                    if (e.Key != Key.S) // thực hiện cập nhật nhóm
                    {
                        return;
                    }

                    if (Keyboard.Modifiers != ModifierKeys.Control)
                    {
                        return;
                    }
                    // thực hiện
                    CAPNHATNHOM();
                }
                
            }
            catch
            {}
        }
        private void CAPNHATNHOM()
        {
            try
            {
                DataRowView drv = dgrGROUP.SelectedItem as DataRowView;
                string ma_khang = drv["MA_KHANG"].ToString();
                //string id_hdon = drv["ID_HDON"].ToString();
                Int64 nhom = Convert.ToInt64(drv["ID_HDON"]);
                int rowindex = dgrGROUP.SelectedIndex;
                if (ds_HDONCHAMNO.Tables["GROUP"].Rows.Count == 0)
                {
                    MessageBox.Show("Không có dữ liệu cập nhật");
                    return;
                }
                if (rowindex < 0)
                {
                    MessageBox.Show("Hãy chọn khách hàng thanh toán cho nhóm!");
                    return;
                }
                else
                {
                    for(int i=0;i<ds_HDONCHAMNO.Tables["GROUP"].Rows.Count;i++)
                    {
                        //bool a =cls.update_NPC_CHAMNO_OFFLINE_NHOM(strMa_dviqly, ds_HDONCHAMNO.Tables["GROUP"].Rows[i]["MA_KHANG"].ToString(), Convert.ToInt64(ds_HDONCHAMNO.Tables["GROUP"].Rows[i]["ID_HDON"].ToString()), thang, nam, nhom, ref maloi);
                        bool a = GlobalServices.Service_NPCUS.update_NPC_CHAMNO_OFFLINE_NHOM(strMa_dviqly, ds_HDONCHAMNO.Tables["GROUP"].Rows[i]["MA_KHANG"].ToString(), Convert.ToInt64(ds_HDONCHAMNO.Tables["GROUP"].Rows[i]["ID_HDON"].ToString()), thang, nam, nhom, ref maloi);
                    }
                }
                ds_HDONCHAMNO.Tables["GROUP"].Rows.Clear();
                dgrGROUP.ItemsSource = null;
                txtTEN_KHANG_GROUP.Text = "";
                bodemGROUP(dgrGROUP);
                group = false;
                MessageBox.Show("Thực hiện xong thánh toán cho nhóm khách hàng!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                Tab_HOADON.IsSelected = true;
                txtTimKiemTenPTu.Focus();
            }
            catch
            { }
        }
        private void cmdCAPNHAT_GROUP_Click(object sender, RoutedEventArgs e)
        {
            CAPNHATNHOM();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ds_HDONCHAMNO.Tables["GROUP"].Rows.Clear();
                dgrGROUP.ItemsSource = null;
                txtTEN_KHANG_GROUP.Text = "";
                group = false;
                bodemGROUP(dgrGROUP);
                Tab_HOADON.IsSelected = true;
                txtTimKiemTenPTu.Focus();
            }
            catch
            { }
        }

        private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    if (e.Key == Key.F) // chuyển con trỏ về ô tìm kiếm
                    {
                        txtTimKiemTenPTu.SelectAll();
                        txtTimKiemTenPTu.Focus();
                        return;
                    }
                    if (e.Key == Key.G) //chuyển con trỏ về ô sổ ghi chỉ số
                    {
                        txtGiaTri.Text = "";
                        txtGiaTri.FocusAutoText();
                        return;
                    }
                    if (e.Key == Key.T)// thực hiện pop
                    {
                        Popup pop = new Popup();
                        //CN_ThongTinKhachHang usc = new CN_ThongTinKhachHang(pop,maloi);
                        //Utility.ShowPopup(gridMain, usc, pop);
                        ////gridMain.IsEnabled = false;
                        //e.Handled = true;
                        return;
                    }
                }
            }
            catch
            {
            }
        }

        private void txtTONGTIENNOP_GROUP_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if (txtTIENNOP.Text.Trim() == "") return;
                    decimal a = 0;
                    a = Convert.ToDecimal(txtTONGTIENNOP_GROUP.Text) - Convert.ToDecimal(format_laitexttheodinhdang(txtTONGTIENGIAO_GROUP.Text));
                    txtTIENTRALAI_GROUP.Text = a.ToString("# ### ### ###");
                    huy_rowchamno();
                    //txtTimKiemTenPTu.Focus();
                }
            }
            catch
            { }
        }

        private void txtTIENNOP_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if (txtTIENNOP.Text.Trim() == "") return;
                    decimal a = 0;
                    a = Convert.ToDecimal(txtTIENNOP.Text) - Convert.ToDecimal(format_laitexttheodinhdang(txtTIENHOADON.Text));
                    txtTIENTRALAI.Text = a.ToString("# ### ### ###");
                    huy_rowchamno();
                    txtTimKiemTenPTu.Focus();
                }
                else
                {
                    //short val;
                    //if (!Int16.TryParse(e.Key.ToString(), out val))
                    //{
                    //    e.Handled = true;
                    //    //MessageBox.Show("hãy nhập số");
                    //    txtTIENNOP.Focus();
                    //    //txtTIENNOP.Text = "";
                    //    return;
                    //}
                    //string a = txtTIENNOP.Text + e.ToString();
                    //text = Convert.ToDecimal(a);
                    //txtTIENNOP.Text = text.ToString("#,###,###,###");
                }
            }
            catch
            { }
        }

       
        private void txtTIENNOP_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            try
            {
                //short val;
                //if (!Int16.TryParse(e.Text, out val))
                //{
                //    e.Handled = true;
                //    //MessageBox.Show("hãy nhập số");
                //    txtTIENNOP.Focus();
                //    //txtTIENNOP.Text = "";
                //    return;
                //}
                //string a = txtTIENNOP.Text + e.Text.ToString();
                //text = Convert.ToDecimal(a);
                //txtTIENNOP.Text = "";
                //txtTIENNOP.Text = text.ToString("#,###,###,###");
                //txtTIENNOP.SelectionStart = txtTIENNOP.Text.Length;
                //e.Handled = false;
                //return;
                //string a = txtTIENNOP.Text + e.Text;
                ////int i = txtTIENNOP.SelectionStart;
                ////string b = a.Substring(0, i) + e.Text + a.Substring(i, a.Length - i);
                //text = Convert.ToDecimal(a);
                //txtTIENNOP.Text = text.ToString("#,###,###,###");
                //txtTIENNOP.SelectionStart = text.ToString().Length;
            }
            catch
            { }
        }

        private void txtTIENNOP_TextInput(object sender, TextCompositionEventArgs e)
        {
            try
            {
                short val;
                if (!Int16.TryParse(e.Text, out val))
                {
                    e.Handled = true;
                    //MessageBox.Show("hãy nhập số");
                    //txtTIENNOP.Focus();
                    //txtTIENNOP.Text = "";
                    return;
                }
            }
            //    string a = txtTIENNOP.Text + e.Text.ToString();
            //    text = Convert.ToDecimal(a);
            //    txtTIENNOP.Text = text.ToString("#,###,###,###");
            //    //txtTIENNOP.SelectionStart = txtTIENNOP.Text.Length;
            //    //e.Handled = false;
            //    //return;
            //    //string a = txtTIENNOP.Text + e.Text;
            //    ////int i = txtTIENNOP.SelectionStart;
            //    ////string b = a.Substring(0, i) + e.Text + a.Substring(i, a.Length - i);
            //    //text = Convert.ToDecimal(a);
            //    //txtTIENNOP.Text = text.ToString("#,###,###,###");
            //    //txtTIENNOP.SelectionStart = text.ToString().Length;
            //}
            catch
            { }
        }

        private void txtTIENNOP_SelectionChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_fSetText)
                {
                    string strTemp = txtTIENNOP.Text;
                    if (String.IsNullOrEmpty(strTemp)) return;
                    int iIndex = strTemp.IndexOf('.');
                    if (iIndex == -1)
                    {
                    }
                    else
                    {
                        string strT = strTemp.Substring(iIndex + 1, 1);
                        if (!String.IsNullOrEmpty(strT))
                        {
                        }
                    }
                    double flTienThuong = double.Parse(txtTIENNOP.Text.Trim(','));
                    _fSetText = false;
                    txtTIENNOP.Text = flTienThuong.ToString("0,00.##");
                }
                else
                {
                    _fSetText = true;
                    // Đưa con trỏ về cuối chuỗi.
                    txtTIENNOP.Select(txtTIENNOP.Text.Length, 0);

                }
            }
            catch (Exception ex)
            {

                //MessageBox.Show("error: " + ex.Message);
            }

        }

        private void txtTONGTIENNOP_GROUP_SelectionChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_fSetTextG)
                {
                    string strTemp = txtTONGTIENNOP_GROUP.Text;
                    if (String.IsNullOrEmpty(strTemp)) return;
                    int iIndex = strTemp.IndexOf('.');
                    if (iIndex == -1)
                    {
                    }
                    else
                    {
                        string strT = strTemp.Substring(iIndex + 1, 1);
                        if (!String.IsNullOrEmpty(strT))
                        {
                        }
                    }
                    double flTienThuong = double.Parse(txtTONGTIENNOP_GROUP.Text.Trim(','));
                    _fSetTextG = false;
                    txtTONGTIENNOP_GROUP.Text = flTienThuong.ToString("0,00.##");
                }
                else
                {
                    _fSetTextG = true;
                    // Đưa con trỏ về cuối chuỗi.
                    txtTONGTIENNOP_GROUP.Select(txtTONGTIENNOP_GROUP.Text.Length, 0);

                }
            }
            catch (Exception ex)
            {

                //MessageBox.Show("error: " + ex.Message);
            }
        }

        
    }
}
